Documentation
¶
Index ¶
- Constants
- Variables
- func AssertFieldViolations(t *testing.T, err error, fvs ...*errdetails.BadRequest_FieldViolation)
- func Code(err error) codes.Code
- func ConvertToConnectError(err error) *connect.Error
- func EnsureConnectError(ctx context.Context) bool
- func Error(c codes.Code, reason, message string) error
- func Errorf(c codes.Code, reason, format string, a ...any) error
- func ExtractDetail[T any](details []any) T
- func FormatField(field string, formatFunc func(string) string) string
- func HTTPErrorWriter(conf *HTTPErrorWriterConfig) func(http.Handler) http.Handler
- func HTTPStatusFromCode(code codes.Code) int
- func NewVProtoHTTPErrorWriter(ib *i18nx.I18N) func(http.Handler) http.Handler
- func Reason(err error) string
- func ReasonFromCode(code codes.Code) statusv1.ErrorReason
- func TranslateError(err error, ib *i18nx.I18N, lang language.Tag) error
- func TranslateStatusErrorOnly(err error, ib *i18nx.I18N, lang language.Tag) (error, bool)
- func UnaryConnectInterceptor(ib *i18nx.I18N, ...) connect.UnaryInterceptorFunc
- func UnaryServerInterceptor(ib *i18nx.I18N) grpc.UnaryServerInterceptor
- func Validate(ctx context.Context, input any) error
- func WriteConnectErrorOnly(errWriter *connect.ErrorWriter, w http.ResponseWriter, r *http.Request, ...) (written bool)
- func WriteVProtoHTTPError(err error, w http.ResponseWriter, r *http.Request) (xerr error)
- type ContextValidator
- type FieldViolation
- func (f *FieldViolation) Description() string
- func (f *FieldViolation) Field() string
- func (f *FieldViolation) Localized() *Localized
- func (f *FieldViolation) LocalizedMessage() *errdetails.LocalizedMessage
- func (f *FieldViolation) Proto() *statusv1.BadRequest_FieldViolation
- func (f *FieldViolation) Reason() string
- func (f *FieldViolation) WithLocalized(key string, args ...any) *FieldViolation
- func (f *FieldViolation) WithLocalizedArgs(args ...any) *FieldViolation
- type FieldViolations
- type HTTPErrorWriterConfig
- type HTTPWriteErrorFunc
- type HTTPWriteErrorInput
- type HTTPWriteErrorOutput
- type Localized
- type Status
- func BadRequest(inputs ...any) *Status
- func Clone(s *Status) *Status
- func Convert(err error) *Status
- func FromError(err error) (s *Status, ok bool)
- func New(c codes.Code, reason, message string) *Status
- func NewCode(code codes.Code, message string) *Status
- func NewCodef(code codes.Code, format string, a ...any) *Status
- func Newf(c codes.Code, reason, format string, a ...any) *Status
- func Wrap(err error, c codes.Code, reason, message string) *Status
- func WrapCode(err error, code codes.Code, message string) *Status
- func WrapCodef(err error, code codes.Code, format string, a ...any) *Status
- func Wrapf(err error, c codes.Code, reason, format string, a ...any) *Status
- func (s *Status) BadRequest() *statusv1.BadRequest
- func (s *Status) Cause() error
- func (s *Status) Code() codes.Code
- func (s *Status) Details() []any
- func (s *Status) Err() error
- func (s *Status) GRPCStatus() *status.Status
- func (s *Status) Localized() *statusv1.Localized
- func (s *Status) Message() string
- func (s *Status) Metadata() map[string]string
- func (s *Status) Reason() string
- func (s *Status) String() string
- func (s *Status) ToFieldViolations(field string) FieldViolations
- func (s *Status) Translated(ib *i18nx.I18N, lang language.Tag) *Status
- func (s *Status) WithCause(cause error) *Status
- func (s *Status) WithCode(c codes.Code) *Status
- func (s *Status) WithDetails(details ...proto.Message) *Status
- func (s *Status) WithFieldViolations(fieldViolations ...*FieldViolation) *Status
- func (s *Status) WithFlattenFieldViolations(inputs ...any) *Status
- func (s *Status) WithLocalized(key string, args ...any) *Status
- func (s *Status) WithLocalizedArgs(args ...any) *Status
- func (s *Status) WithMessage(message string) *Status
- func (s *Status) WithMessagef(format string, a ...any) *Status
- func (s *Status) WithMetadata(md map[string]string) *Status
- func (s *Status) WithReason(reason string) *Status
- type StatusError
- type Validator
Constants ¶
const ErrorReasonProtoGenValidate = "PROTO_GEN_VALIDATE"
const HeaderEnsureConnectError = "x-ensure-connect-error"
Variables ¶
var AllowHeaders = []string{ http.CanonicalHeaderKey(HeaderEnsureConnectError), }
Functions ¶
func AssertFieldViolations ¶ added in v3.2.0
func AssertFieldViolations(t *testing.T, err error, fvs ...*errdetails.BadRequest_FieldViolation)
func ConvertToConnectError ¶
func EnsureConnectError ¶
func ExtractDetail ¶ added in v3.2.0
func FormatField ¶ added in v3.2.0
FormatField formats a dotted field path by applying a formatting function to each segment while preserving array index notations (e.g., [0], [1]).
Parameters:
- field: The original field path (e.g., "user_info.addresses[0].street_name")
- formatFunc: Function to apply to each field segment (e.g., lo.CamelCase)
Returns:
- The formatted field path with proper array index preservation
Example:
FormatField("user_info.addresses[0].street_name", lo.CamelCase)
Returns: "userInfo.addresses[0].streetName"
func HTTPErrorWriter ¶
func HTTPErrorWriter(conf *HTTPErrorWriterConfig) func(http.Handler) http.Handler
func HTTPStatusFromCode ¶
from connectCodeToHTTP of connect library
func ReasonFromCode ¶
func ReasonFromCode(code codes.Code) statusv1.ErrorReason
ReasonFromCode maps gRPC codes to their corresponding ErrorReason values
func TranslateError ¶
TranslateError translates error messages and field violations using the provided i18n instance and language. Returns the original error if translation is not possible or if localized details already exist.
Translation priority:
- If LocalizedMessage already exists -> skip translation (highest priority)
- If Localized template exists -> translate template (medium priority)
- Use error reason for translation -> fallback (lowest priority)
func TranslateStatusErrorOnly ¶
TranslateStatusErrorOnly translates only StatusError types, returning the error and a boolean indicating success
func UnaryConnectInterceptor ¶
func UnaryConnectInterceptor(ib *i18nx.I18N, shouldConvert func(ctx context.Context, req connect.AnyRequest) bool) connect.UnaryInterceptorFunc
func UnaryServerInterceptor ¶
func UnaryServerInterceptor(ib *i18nx.I18N) grpc.UnaryServerInterceptor
func WriteConnectErrorOnly ¶
func WriteConnectErrorOnly(errWriter *connect.ErrorWriter, w http.ResponseWriter, r *http.Request, err error) (written bool)
func WriteVProtoHTTPError ¶
Types ¶
type ContextValidator ¶ added in v3.2.0
type FieldViolation ¶ added in v3.2.0
type FieldViolation struct {
// contains filtered or unexported fields
}
FieldViolation represents a field-level validation violation with localization capability
Priority order for localized messages:
- LocalizedMessage (highest priority - pre-translated, ready to use)
- Localized (lower priority - template that needs translation via interceptor)
func NewFieldViolation ¶ added in v3.2.0
func NewFieldViolation(field, reason, description string) *FieldViolation
NewFieldViolation creates a new field validation violation. The reason serves as the error identifier and will be used as the i18n key fallback during translation.
func NewFieldViolationf ¶ added in v3.2.0
func NewFieldViolationf(field, reason, format string, args ...any) *FieldViolation
NewFieldViolationf creates a new field validation violation with a formatted description.
func (*FieldViolation) Description ¶ added in v3.2.0
func (f *FieldViolation) Description() string
Description returns the human-readable description of the violation.
func (*FieldViolation) Field ¶ added in v3.2.0
func (f *FieldViolation) Field() string
Field returns the field name that caused the violation.
func (*FieldViolation) Localized ¶ added in v3.2.0
func (f *FieldViolation) Localized() *Localized
Localized returns the localization template if set. Returns nil if no localization template is available.
func (*FieldViolation) LocalizedMessage ¶ added in v3.2.0
func (f *FieldViolation) LocalizedMessage() *errdetails.LocalizedMessage
LocalizedMessage returns the pre-translated message if available. Returns nil if no pre-translated message is set.
func (*FieldViolation) Proto ¶ added in v3.2.0
func (f *FieldViolation) Proto() *statusv1.BadRequest_FieldViolation
Proto converts FieldViolation to protobuf message
func (*FieldViolation) Reason ¶ added in v3.2.0
func (f *FieldViolation) Reason() string
Reason returns the error reason code.
func (*FieldViolation) WithLocalized ¶ added in v3.2.0
func (f *FieldViolation) WithLocalized(key string, args ...any) *FieldViolation
WithLocalized sets a custom i18n key and template arguments. This sets a specific i18n key instead of relying on the reason as fallback during translation.
func (*FieldViolation) WithLocalizedArgs ¶ added in v3.2.0
func (f *FieldViolation) WithLocalizedArgs(args ...any) *FieldViolation
WithLocalizedArgs sets template arguments for i18n. Preserves the existing localized key if present, or leaves it empty for the translator to use reason as fallback. This is useful when you want to add template arguments without setting a specific i18n key.
type FieldViolations ¶ added in v3.2.0
type FieldViolations []*FieldViolation
func FlattenFieldViolations ¶ added in v3.2.0
func FlattenFieldViolations(inputs ...any) (FieldViolations, error)
FlattenFieldViolations flattens various field violation types into a unified FieldViolations slice. Supports *FieldViolation, []*FieldViolation, FieldViolations, and their protobuf equivalents. Mixed types are allowed in a single call.
Note: For error and *Status inputs, use ToFieldViolations(err, field) or status.ToFieldViolations(field) first to specify the field name, then pass the result to this function.
func PrependField ¶ added in v3.2.0
func PrependField(field string, fvs ...*FieldViolation) FieldViolations
PrependField prepends a field name to the field name of each field violation.
func ToFieldViolations ¶ added in v3.2.0
func ToFieldViolations(err error, field string) FieldViolations
ToFieldViolations converts any error to field violations for the specified field. Simple behavior:
- If field is empty: returns only nested field violations without prefix
- If field is non-empty: returns only nested field violations with the specified field prefix
This design extracts meaningful field-level violations from container errors.
func (FieldViolations) PrependField ¶ added in v3.2.0
func (fvs FieldViolations) PrependField(field string) FieldViolations
type HTTPErrorWriterConfig ¶
func (*HTTPErrorWriterConfig) WithHTTPWriteErrorHook ¶
func (c *HTTPErrorWriterConfig) WithHTTPWriteErrorHook(hooks ...hook.Hook[HTTPWriteErrorFunc]) *HTTPErrorWriterConfig
type HTTPWriteErrorFunc ¶
type HTTPWriteErrorFunc func(ctx context.Context, input *HTTPWriteErrorInput) (*HTTPWriteErrorOutput, error)
func VProtoHTTPWriteErrorHook ¶
func VProtoHTTPWriteErrorHook(next HTTPWriteErrorFunc) HTTPWriteErrorFunc
type HTTPWriteErrorInput ¶
type HTTPWriteErrorInput struct {
Conf *HTTPErrorWriterConfig
W http.ResponseWriter
R *http.Request
Err error
}
type HTTPWriteErrorOutput ¶
type HTTPWriteErrorOutput struct {
Written bool
}
type Localized ¶ added in v3.2.0
type Localized struct {
// contains filtered or unexported fields
}
Localized represents a localized message
func LocalizedFromProto ¶ added in v3.2.0
type Status ¶
type Status struct {
// contains filtered or unexported fields
}
func BadRequest ¶
BadRequest creates a new Status with the InvalidArgument code and a flattened list of field violations.
func New ¶
New creates a Status with the specified code, reason, and message.
For non-OK status codes, it automatically captures a stacktrace at creation time, which provides valuable debugging context without manual instrumentation.
Parameters:
- c: The status code indicating the type of status
- reason: A string identifier used as the error reason and i18n key fallback during translation
- message: A human-readable message for debugging purposes
The reason serves as both the error identifier and the i18n key. The reason is immediately fixed as the i18n key at creation time. Use WithLocalized() to override with a specific i18n key and args if needed. Use WithLocalizedArgs() to add template arguments while preserving the current key. Returns a Status object that can be further enriched with metadata or localization.
func NewCode ¶
NewCode creates a Status with automatically derived reason from the gRPC code. This is a convenience function that uses ReasonFromCode to generate the reason.
func NewCodef ¶
NewCodef creates a Status with automatically derived reason and formatted message. This is a convenience function that uses ReasonFromCode to generate the reason.
func WrapCode ¶
WrapCode wraps an error with automatically derived reason from the gRPC code. This is a convenience function that uses ReasonFromCode to generate the reason.
func WrapCodef ¶
WrapCodef wraps an error with automatically derived reason and formatted message. This is a convenience function that uses ReasonFromCode to generate the reason.
func (*Status) BadRequest ¶ added in v3.2.0
func (s *Status) BadRequest() *statusv1.BadRequest
func (*Status) Err ¶
Err converts the Status to an error interface.
The returned error type is either:
- nil: When Status.Code() is codes.OK
- *StatusError: An error that implements both error and GRPCStatus interfaces
func (*Status) GRPCStatus ¶
func (*Status) ToFieldViolations ¶ added in v3.2.0
func (s *Status) ToFieldViolations(field string) FieldViolations
ToFieldViolations converts this Status to field violations for the specified field
func (*Status) Translated ¶ added in v3.2.0
Translated returns a new Status with translated messages and field violations.
Translation priority:
- If LocalizedMessage already exists -> skip translation (highest priority)
- If Localized template exists -> translate template (medium priority)
- Use error reason for translation -> fallback (lowest priority)
func (*Status) WithDetails ¶ added in v3.2.0
func (*Status) WithFieldViolations ¶ added in v3.2.0
func (s *Status) WithFieldViolations(fieldViolations ...*FieldViolation) *Status
WithFieldViolations adds multiple field-level validation violations in batch. Multiple violations for the same field are allowed and will be appended.
func (*Status) WithFlattenFieldViolations ¶ added in v3.2.0
WithFlattenFieldViolations accepts various types of field violation inputs and flattens them. Supports *FieldViolation, []*FieldViolation, FieldViolations, and their protobuf equivalents. Mixed types are allowed in a single call for maximum flexibility.
Note: For error and *Status inputs, use ToFieldViolations(err, field) or status.ToFieldViolations(field) first to specify the field name, then pass the result to this function.
func (*Status) WithLocalizedArgs ¶ added in v3.2.0
WithLocalizedArgs sets template arguments for i18n. Preserves the existing localized key and adds/replaces the template arguments. Since the key is always set (either at creation time or by WithLocalized), no fallback logic is needed.
func (*Status) WithMessage ¶ added in v3.2.0
func (*Status) WithMessagef ¶ added in v3.2.0
func (*Status) WithReason ¶
type StatusError ¶
type StatusError struct {
// contains filtered or unexported fields
}
func (*StatusError) Cause ¶
func (e *StatusError) Cause() error
func (*StatusError) Error ¶
func (e *StatusError) Error() string
func (*StatusError) GRPCStatus ¶
func (e *StatusError) GRPCStatus() *status.Status
func (*StatusError) Is ¶
func (e *StatusError) Is(target error) bool
func (*StatusError) Status ¶
func (e *StatusError) Status() *Status
func (*StatusError) Unwrap ¶
func (e *StatusError) Unwrap() error