statusx

package
v3.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2025 License: MIT Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const ErrorReasonProtoGenValidate = "PROTO_GEN_VALIDATE"
View Source
const HeaderEnsureConnectError = "x-ensure-connect-error"

Variables

Functions

func AssertFieldViolations added in v3.2.0

func AssertFieldViolations(t *testing.T, err error, fvs ...*errdetails.BadRequest_FieldViolation)

func Code

func Code(err error) codes.Code

func ConvertToConnectError

func ConvertToConnectError(err error) *connect.Error

func EnsureConnectError

func EnsureConnectError(ctx context.Context) bool

func Error

func Error(c codes.Code, reason, message string) error

func Errorf

func Errorf(c codes.Code, reason, format string, a ...any) error

func ExtractDetail added in v3.2.0

func ExtractDetail[T any](details []any) T

func FormatField added in v3.2.0

func FormatField(field string, formatFunc func(string) string) string

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

func HTTPStatusFromCode(code codes.Code) int

from connectCodeToHTTP of connect library

func NewVProtoHTTPErrorWriter

func NewVProtoHTTPErrorWriter(ib *i18nx.I18N) func(http.Handler) http.Handler

func Reason

func Reason(err error) string

func ReasonFromCode

func ReasonFromCode(code codes.Code) statusv1.ErrorReason

ReasonFromCode maps gRPC codes to their corresponding ErrorReason values

func TranslateError

func TranslateError(err error, ib *i18nx.I18N, lang language.Tag) error

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:

  1. If LocalizedMessage already exists -> skip translation (highest priority)
  2. If Localized template exists -> translate template (medium priority)
  3. Use error reason for translation -> fallback (lowest priority)

func TranslateStatusErrorOnly

func TranslateStatusErrorOnly(err error, ib *i18nx.I18N, lang language.Tag) (error, bool)

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 Validate added in v3.2.0

func Validate(ctx context.Context, input any) error

func WriteConnectErrorOnly

func WriteConnectErrorOnly(errWriter *connect.ErrorWriter, w http.ResponseWriter, r *http.Request, err error) (written bool)

func WriteVProtoHTTPError

func WriteVProtoHTTPError(err error, w http.ResponseWriter, r *http.Request) (xerr error)

Types

type ContextValidator added in v3.2.0

type ContextValidator interface {
	Validate(ctx context.Context) error
}

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:

  1. LocalizedMessage (highest priority - pre-translated, ready to use)
  2. 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

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

type HTTPErrorWriterConfig struct {
	I18N *i18nx.I18N
	// contains filtered or unexported fields
}

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

func LocalizedFromProto(pb *statusv1.Localized) *Localized

func (*Localized) Args added in v3.2.0

func (l *Localized) Args() []any

func (*Localized) Key added in v3.2.0

func (l *Localized) Key() string

func (*Localized) Proto added in v3.2.0

func (l *Localized) Proto() *statusv1.Localized

type Status

type Status struct {
	// contains filtered or unexported fields
}

func BadRequest

func BadRequest(inputs ...any) *Status

BadRequest creates a new Status with the InvalidArgument code and a flattened list of field violations.

func Clone

func Clone(s *Status) *Status

func Convert

func Convert(err error) *Status

func FromError

func FromError(err error) (s *Status, ok bool)

func New

func New(c codes.Code, reason, message string) *Status

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

func NewCode(code codes.Code, message string) *Status

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

func NewCodef(code codes.Code, format string, a ...any) *Status

NewCodef creates a Status with automatically derived reason and formatted message. This is a convenience function that uses ReasonFromCode to generate the reason.

func Newf

func Newf(c codes.Code, reason, format string, a ...any) *Status

func Wrap

func Wrap(err error, c codes.Code, reason, message string) *Status

func WrapCode

func WrapCode(err error, code codes.Code, message string) *Status

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

func WrapCodef(err error, code codes.Code, format string, a ...any) *Status

WrapCodef wraps an error with automatically derived reason and formatted message. This is a convenience function that uses ReasonFromCode to generate the reason.

func Wrapf

func Wrapf(err error, c codes.Code, reason, format string, a ...any) *Status

func (*Status) BadRequest added in v3.2.0

func (s *Status) BadRequest() *statusv1.BadRequest

func (*Status) Cause

func (s *Status) Cause() error

func (*Status) Code

func (s *Status) Code() codes.Code

func (*Status) Details

func (s *Status) Details() []any

func (*Status) Err

func (s *Status) Err() error

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 (s *Status) GRPCStatus() *status.Status

func (*Status) Localized

func (s *Status) Localized() *statusv1.Localized

func (*Status) Message

func (s *Status) Message() string

func (*Status) Metadata

func (s *Status) Metadata() map[string]string

func (*Status) Reason

func (s *Status) Reason() string

func (*Status) String

func (s *Status) String() string

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

func (s *Status) Translated(ib *i18nx.I18N, lang language.Tag) *Status

Translated returns a new Status with translated messages and field violations.

Translation priority:

  1. If LocalizedMessage already exists -> skip translation (highest priority)
  2. If Localized template exists -> translate template (medium priority)
  3. Use error reason for translation -> fallback (lowest priority)

func (*Status) WithCause

func (s *Status) WithCause(cause error) *Status

func (*Status) WithCode

func (s *Status) WithCode(c codes.Code) *Status

func (*Status) WithDetails added in v3.2.0

func (s *Status) WithDetails(details ...proto.Message) *Status

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

func (s *Status) WithFlattenFieldViolations(inputs ...any) *Status

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) WithLocalized

func (s *Status) WithLocalized(key string, args ...any) *Status

func (*Status) WithLocalizedArgs added in v3.2.0

func (s *Status) WithLocalizedArgs(args ...any) *Status

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 (s *Status) WithMessage(message string) *Status

func (*Status) WithMessagef added in v3.2.0

func (s *Status) WithMessagef(format string, a ...any) *Status

func (*Status) WithMetadata

func (s *Status) WithMetadata(md map[string]string) *Status

func (*Status) WithReason

func (s *Status) WithReason(reason string) *Status

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) Format

func (e *StatusError) Format(s fmt.State, verb rune)

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

type Validator added in v3.2.0

type Validator interface {
	Validate() error
}

Directories

Path Synopsis
gen

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL