Documentation
¶
Index ¶
- Variables
- func AllowInternalLogs(allow bool)
- func AllowRuntimePanics(allow bool)
- func AllowStaticMutations(allow bool, shouldPanic bool)
- func BackoffConstant(d time.Duration) func(int) time.Duration
- func BackoffExponential(base time.Duration) func(int) time.Duration
- func BackoffLinear(step time.Duration) func(int) time.Duration
- func ExportIDList() ([]byte, error)
- func GetDebug(err error) ([]string, bool)
- func GetInternalMessage(err error) string
- func GetMessage(err error) string
- func GetMeta(err error, key string) (any, bool)
- func GetTraces(err error) ([]string, bool)
- func Is(err error, id ErrorID) bool
- func IsDomain(err error) bool
- func IsRetryableDefault(err error) bool
- func IsSystem(err error) bool
- func IsTrusted(err error) bool
- func Must(err error)
- func MustRegisterTranslator(t Translator)
- func On(t HookType, fn any)
- func OnCreate(fn func(*Error, map[string]any))
- func OnForm(fn func(ErrorID, *Error))
- func OnFromFail(fn func(error))
- func OnFromSuccess(fn func(error, *Error))
- func OnLog(fn func(*Error, map[string]any))
- func OnMap(fn func(*Error, map[string]any))
- func OnMatch(fn func(*Error, map[string]any))
- func OnTrace(fn func(*Error, map[string]any))
- func OnTranslate(fn func(*Error, map[string]any))
- func OnWrap(fn func(*Error, error))
- func OverrideAllowIDRuntimePanics(allow bool)
- func OverrideAllowIDRuntimeRegistrationForTestingOnly(allow bool)
- func Register(def ErrorDefinition)
- func RegisterMany(defs ...*ErrorDefinition)
- func RegisterMapper(mapper Mapper)
- func RegisterTranslations(locale string, msgs map[ErrorID]string)
- func RegisterTranslator(t Translator) error
- func Retry(fn func() error) error
- func RetryCFG(config RetryConfig, fn func() error) error
- func RetryValue[T any](fn func() (T, error)) (T, error)
- func RetryValueCFG[T any](config RetryConfig, fn func() (T, error)) (T, error)
- func SetDefaultLocale(locale string)
- func SetLogger(logger Logger)
- func SetRetryConfig(config *RetryConfig)
- func SetTracer(tracer Tracer)
- func Translate(err *Error, translatorName string) (any, error)
- func TranslateAs[T any](err *Error, translatorName string) (T, error)
- func TranslateAsFrom[T any](r *Registry, err *Error, translatorName string) (T, error)
- func ValidateIDs()
- func WithJitter(delay func(int) time.Duration, jitterFraction float64) func(int) time.Duration
- type Error
- func As(err error) (*Error, bool)
- func Fast(id ErrorID, message string) *Error
- func Form(id ErrorID, defaultMsg string, isSystem bool, meta map[string]any, ...) *Error
- func From(err error) *Error
- func FromWithMsg(err error, message string) *Error
- func MustNew(id ErrorID) *Error
- func New(id ErrorID) *Error
- func Newf(id ErrorID, format string, args ...interface{}) *Error
- func Wrap(id ErrorID, cause error) *Error
- func WrapMsg(id ErrorID, message string, cause error) *Error
- func (e *Error) AddLocalization(locale string, msg string) *Error
- func (e *Error) AddLocalizations(msgs map[string]string) *Error
- func (e *Error) AddMeta(key string, value any) *Error
- func (e *Error) Debug(debug string) *Error
- func (e *Error) Debugs(debug ...string) *Error
- func (e *Error) Domain() *Error
- func (e *Error) Dump() map[string]any
- func (e *Error) Error() string
- func (e *Error) GetLocalized() string
- func (e *Error) GetRendered() string
- func (e *Error) Internal(msg string) *Error
- func (e *Error) Internalf(format string, args ...any) *Error
- func (e *Error) IsTrusted() bool
- func (e *Error) Localize() *Error
- func (e *Error) Log() *Error
- func (e *Error) LogAndRecord() *Error
- func (e *Error) LogAndRecordCtx(ctx context.Context) *Error
- func (e *Error) LogCtx(ctx context.Context) *Error
- func (e *Error) MergeMeta(data map[string]any) *Error
- func (e *Error) Msg(msg string) *Error
- func (e *Error) Msgf(format string, args ...any) *Error
- func (e *Error) Record() *Error
- func (e *Error) RecordCtx(ctx context.Context) *Error
- func (e *Error) Render() *Error
- func (e *Error) System() *Error
- func (e *Error) Trace(trace string) *Error
- func (e *Error) Traces(trace ...string) *Error
- func (e *Error) Unwrap() error
- func (e *Error) Validation(field, message string) *Error
- func (e *Error) Validations(errs []ValidationError) *Error
- func (e *Error) With(cause error) *Error
- func (e *Error) WithArgs(args ...any) *Error
- func (e *Error) WithLocale(locale string) *Error
- func (e *Error) WithMeta(data map[string]any) *Error
- type ErrorChain
- func (c *ErrorChain) Catch(fn func(*Error) *Error) *ErrorChain
- func (c *ErrorChain) Error() *Error
- func (c *ErrorChain) Finally(fn func()) *ErrorChain
- func (c *ErrorChain) OnError(fn func(*Error)) *ErrorChain
- func (c *ErrorChain) Step() int
- func (c *ErrorChain) Then(fn func() error) *ErrorChain
- func (c *ErrorChain) ThenCtx(stepName string, fn func() error) *ErrorChain
- func (c *ErrorChain) ThenCtxIf(condition bool, stepName string, fn func() error) *ErrorChain
- func (c *ErrorChain) ThenIf(condition bool, fn func() error) *ErrorChain
- func (c *ErrorChain) Unwrap() error
- func (c *ErrorChain) Valid() bool
- type ErrorDefinition
- type ErrorGroup
- func (g *ErrorGroup) Add(err error) *ErrorGroup
- func (g *ErrorGroup) Addf(id ErrorID, format string, args ...interface{}) *ErrorGroup
- func (g *ErrorGroup) Any(match func(*Error) bool) bool
- func (g *ErrorGroup) Error() string
- func (g *ErrorGroup) Errors() []*Error
- func (g *ErrorGroup) First() *Error
- func (g *ErrorGroup) HasErrors() bool
- func (g *ErrorGroup) Last() *Error
- func (g *ErrorGroup) Len() int
- func (g *ErrorGroup) Reset() *ErrorGroup
- func (g *ErrorGroup) ToError() *Error
- func (g *ErrorGroup) Unwrap() []error
- type ErrorID
- type ErrorMatcher
- func (m *ErrorMatcher) Case(id ErrorID, handler func(*Error)) *ErrorMatcher
- func (m *ErrorMatcher) CaseAny(handler func(*Error), ids ...ErrorID) *ErrorMatcher
- func (m *ErrorMatcher) CaseDomain(handler func(*Error)) *ErrorMatcher
- func (m *ErrorMatcher) CaseSystem(handler func(*Error)) *ErrorMatcher
- func (m *ErrorMatcher) Default(handler func(error))
- type ErrorType
- type Frame
- type HookType
- type Hooks
- type IDRegistry
- func (r *IDRegistry) ExportIDList() ([]byte, error)
- func (r *IDRegistry) GetAllIDs() []ErrorID
- func (r *IDRegistry) ID(name, domain string, static bool, level, number int) ErrorID
- func (r *IDRegistry) OverrideAllowRuntimePanics(allow bool)
- func (r *IDRegistry) Reset()
- func (r *IDRegistry) ValidateIDs()
- type Logger
- type Mapper
- type MapperList
- type Registry
- func (r *Registry) AllowInternalLogs(allow bool)
- func (r *Registry) AllowStaticMutations(allow bool, shouldPanic bool)
- func (r *Registry) Form(id ErrorID, defaultMsg string, isSystem bool, meta map[string]any, ...) *Error
- func (r *Registry) From(err error) *Error
- func (r *Registry) New(id ErrorID) *Error
- func (r *Registry) On(t HookType, fn any)
- func (r *Registry) Register(err *Error)
- func (r *Registry) RegisterMany(defs ...*ErrorDefinition)
- func (r *Registry) RegisterMapper(mapper Mapper)
- func (r *Registry) RegisterTranslations(locale string, msgs map[ErrorID]string)
- func (r *Registry) RegisterTranslator(t Translator) error
- func (r *Registry) SetDefaultLocale(locale string)
- func (r *Registry) SetLogger(logger Logger)
- func (r *Registry) SetTracer(tracer Tracer)
- func (r *Registry) Translate(err *Error, translatorName string) (out any, retErr error)
- type RetryConfig
- type Tracer
- type TranslationRegistry
- type Translator
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
var ErrMultipleErrors = Form(MultipleErrors, "multiple errors occurred", false, nil)
var ErrNoMapperRegistered = Form(NoMapperRegistered, "no mapper is registered in the registry", true, nil)
var ErrNotMatchedInAnyMapper = Form(NotMatchedInAnyMapper, "error wasn't matched/mapped by any mapper", true, nil)
var ErrTranslateNotFound = Form(TranslateNotFound, "couldn't find translator", true, nil)
var ErrTranslatePanic = Form(TranslatePanic, "translator panicked during translation", true, nil)
var ErrTranslateUnsupportedError = Form(TranslateUnsupportedError, "error not supported by %s translator", true, nil, "UNNAMED")
var ErrTranslateUntrustedError = Form(TranslateUntrustedError, "tried translating unregistered error", true, nil)
var ErrTranslateWrongType = Form(TranslateWrongType, "translator returned unexpected type", true, nil)
var ErrTranslatorAlreadyRegistered = Form(TranslatorAlreadyRegistered, "translator already registered", true, nil)
var ErrTranslatorNameEmpty = Form(TranslatorNameEmpty, "translator must have a non-empty name", true, nil)
var ErrTranslatorNil = Form(TranslatorNil, "cannot register nil translator", true, nil)
var ErrUnknownError = Form(UnknownError, "unknown error", true, nil)
var ErrUnregisteredError = Form(UnregisteredError, "error with ID(%s) is not registered in the registry", true, nil, "ID NOT SET")
var MultipleErrors = internalID(0, 6, false, "FailMultipleErrors")
MultipleErrors is raised when multiple errors are aggregated in ErrorGroup
var NoMapperRegistered = internalID(0, 12, false, "FailNoMapperRegistered")
var NotMatchedInAnyMapper = internalID(0, 11, false, "FailNotMatchedInAnyMapper")
var RuntimeIDInvalid = internalID(9, 16, true, "FailRuntimeIDInvalid")
var TranslateNotFound = internalID(0, 2, false, "FailTranslatorNotFound")
var TranslatePanic = internalID(0, 4, false, "FailTranslatorPanic")
var TranslateUnsupportedError = internalID(0, 3, false, "FailTranslateUnsupportedError")
var TranslateUntrustedError = internalID(0, 1, false, "FailTranslateUntrustedError")
var TranslateWrongType = internalID(0, 5, false, "FailTranslateWrongType")
var TranslatorAlreadyRegistered = internalID(0, 13, false, "FailTranslatorAlreadyRegistered")
var TranslatorNameEmpty = internalID(0, 15, true, "FailTranslatorNameEmpty")
var TranslatorNil = internalID(0, 14, true, "FailTranslatorNil")
var UnknownError = internalID(0, 7, false, "FailUnknownError")
var UnregisteredError = internalID(0, 0, false, "FailUnregisteredError")
Functions ¶
func AllowInternalLogs ¶ added in v1.1.8
func AllowInternalLogs(allow bool)
AllowInternalLogs enables or disables internal library logging. When enabled, the library will log warnings and debug information about error processing, such as:
- Double calls to From()
- Unmapped errors
- Mapper registration issues
This is useful for debugging integration issues but should be disabled in production to avoid log spam. Default is false.
Example:
fail.AllowInternalLogs(true) // Enable logging fail.AllowInternalLogs(false) // Disable logging (default)
func AllowRuntimePanics ¶ added in v1.1.10
func AllowRuntimePanics(allow bool)
AllowRuntimePanics controls whether the library may panic at runtime. When true, operations that would normally log warnings or fail silently will instead panic immediately (e.g., modifying static errors). When false (default), the library avoids panics and uses error logging or silent failures where appropriate.
Note: The ID() method will always panic regardless of this setting.
Enabling this is recommended during development and testing to catch programming errors early, but should typically be disabled in production.
func AllowStaticMutations ¶ added in v1.1.10
AllowStaticMutations controls whether static errors in the global registry can be mutated. When set to false (default), builder methods on static errors will silently return the original error without modifications. When set to true, shoudlPanic is ignored and mutations are allowed but warnings are logged if internal logging is enabled.
If shouldPanic is true and allow is false, attempts to modify static errors will panic instead of failing silently. This overrides the default silent behavior.
This is a convenience wrapper for global.AllowStaticMutations(allow, shouldPanic).
func ExportIDList ¶
ExportIDList returns all registered error IDs as JSON bytes
func GetInternalMessage ¶
GetInternalMessage extracts the internal message from an error
func GetMessage ¶
GetMessage extracts the user-facing message from any error
func IsRetryableDefault ¶
func MustRegisterTranslator ¶
func MustRegisterTranslator(t Translator)
func OnFromFail ¶ added in v1.1.3
func OnFromFail(fn func(error))
func OnFromSuccess ¶ added in v1.1.3
func OnTranslate ¶
func OverrideAllowIDRuntimePanics ¶ added in v1.1.11
func OverrideAllowIDRuntimePanics(allow bool)
OverrideAllowIDRuntimePanics sets global id registry override
func OverrideAllowIDRuntimeRegistrationForTestingOnly ¶ added in v1.1.11
func OverrideAllowIDRuntimeRegistrationForTestingOnly(allow bool)
OverrideAllowIDRuntimeRegistrationForTestingOnly sets global id registry override for tests
func Register ¶
func Register(def ErrorDefinition)
Register adds an error definition to the global registry
func RegisterMany ¶
func RegisterMany(defs ...*ErrorDefinition)
RegisterMany registers multiple error definitions at once
func RegisterTranslations ¶
RegisterTranslations adds translations for a locale on the global registry
func RegisterTranslator ¶
func RegisterTranslator(t Translator) error
RegisterTranslator adds a translator for converting errors to other formats
func RetryCFG ¶
func RetryCFG(config RetryConfig, fn func() error) error
RetryCFG executes a function with retries using the passed config
func RetryValue ¶
RetryValue retries a function that returns (T, error)
func RetryValueCFG ¶
func RetryValueCFG[T any](config RetryConfig, fn func() (T, error)) (T, error)
func SetDefaultLocale ¶
func SetDefaultLocale(locale string)
SetDefaultLocale sets the fallback locale for the global registry
func SetLogger ¶
func SetLogger(logger Logger)
SetLogger sets the custom logging solution to the registry
func SetRetryConfig ¶
func SetRetryConfig(config *RetryConfig)
func SetTracer ¶
func SetTracer(tracer Tracer)
SetTracer sets the custom tracing solution to the registry
func TranslateAsFrom ¶
func ValidateIDs ¶
func ValidateIDs()
ValidateIDs checks for gaps and duplicates. Call in main() after all init().
Types ¶
type Error ¶
type Error struct {
// Required fields
ID ErrorID // Unique trusted identifier
Message string // User-facing message
InternalMessage string // Internal/debug message (optional but recommended)
Cause error // The underlying error that caused this
IsSystem bool // true = infrastructure/unexpected, false = domain/expected
Args []any // Captured arguments for localization
Locale string // Target locale for this error instance
// Optional structured data
Meta map[string]any // Arbitrary metadata (traces, validation errors, etc.)
// contains filtered or unexported fields
}
Error is the core error type that all domain errors implement
func Form ¶
func Form(id ErrorID, defaultMsg string, isSystem bool, meta map[string]any, defaultArgs ...any) *Error
Form creates, registers, and returns an error in one call This is a convenience function for defining error sentinels
WARNING Only use package level sentinel errors that are created by Form in non-concurrent environments For concurrent environment prefer calling New with the error ID
Example:
var ErrUserNotFound = fail.Form(UserNotFound, "user not found", false, nil)
This is equivalent to:
fail.Register(fail.ErrorDefinition{
ID: UserNotFound,
DefaultMessage: "user not found",
IsSystem: false,
})
var ErrUserNotFound = fail.New(UserNotFound)
func FromWithMsg ¶
FromWithMsg ingests a generic error and adds a custom message
func (*Error) AddLocalization ¶
AddLocalization adds a translation for this error's ID to its registry If localization already exists for this locale+ID, does nothing (idempotent) Returns the original error unmodified for chaining
func (*Error) AddLocalizations ¶
AddLocalizations adds multiple translations at once
func (*Error) GetLocalized ¶
GetLocalized returns the localized message template as string (read-only, no modification)
func (*Error) GetRendered ¶
GetRendered returns the fully rendered message as string (read-only, no modification)
func (*Error) Localize ¶
Localize resolves the translated message template for this error's locale Stores result in e.Message, returns *Error for chaining
func (*Error) LogAndRecord ¶
LogAndRecord logs and traces the error
func (*Error) Render ¶
Render formats the error's message template with its arguments Stores result in e.Message, returns *Error for chaining
func (*Error) Validation ¶
Validation adds a validation error to metadata
func (*Error) Validations ¶
func (e *Error) Validations(errs []ValidationError) *Error
Validations adds multiple validation errors at once
func (*Error) WithLocale ¶
WithLocale sets the target locale for this error
type ErrorChain ¶
type ErrorChain struct {
// contains filtered or unexported fields
}
ErrorChain enables fluent error handling with *Error as first-class citizen internally Accepts standard Go error functions externally, converts immediately to *Error
func Chain ¶
func Chain(fn func() error) *ErrorChain
Chain starts a new error chain, immediately executing the first step The error is normalized to *Error via From() on entry
Example:
err := fail.Chain(validateRequest).
Then(checkPermissions).
ThenCtx("database", saveData).
Error()
func ChainCtx ¶
func ChainCtx(stepName string, fn func() error) *ErrorChain
ChainCtx starts a chain with immediate named context
func (*ErrorChain) Catch ¶
func (c *ErrorChain) Catch(fn func(*Error) *Error) *ErrorChain
Catch transforms the error, enabling recovery or enrichment fn receives the current *Error and returns modified *Error
func (*ErrorChain) Error ¶
func (c *ErrorChain) Error() *Error
Error returns the final *Error or nil Returns concrete type for rich error handling (ID, Meta, Cause, etc.)
func (*ErrorChain) Finally ¶
func (c *ErrorChain) Finally(fn func()) *ErrorChain
Finally executes cleanup regardless of error state
func (*ErrorChain) OnError ¶
func (c *ErrorChain) OnError(fn func(*Error)) *ErrorChain
OnError executes callback if chain has failed (for logging/metrics/cleanup)
func (*ErrorChain) Step ¶
func (c *ErrorChain) Step() int
Step returns count of successfully completed steps
func (*ErrorChain) Then ¶
func (c *ErrorChain) Then(fn func() error) *ErrorChain
Then executes the next step if no error has occurred Automatically converts returned error to *Error via From()
func (*ErrorChain) ThenCtx ¶
func (c *ErrorChain) ThenCtx(stepName string, fn func() error) *ErrorChain
ThenCtx executes with named step context for observability
func (*ErrorChain) ThenCtxIf ¶
func (c *ErrorChain) ThenCtxIf(condition bool, stepName string, fn func() error) *ErrorChain
ThenCtxIf executes named step conditionally
func (*ErrorChain) ThenIf ¶
func (c *ErrorChain) ThenIf(condition bool, fn func() error) *ErrorChain
ThenIf executes conditionally only if condition is true and no prior error
func (*ErrorChain) Unwrap ¶
func (c *ErrorChain) Unwrap() error
Unwrap implements error interface for compatibility
func (*ErrorChain) Valid ¶
func (c *ErrorChain) Valid() bool
Valid returns true if no errors occurred (all steps succeeded)
type ErrorDefinition ¶
type ErrorDefinition struct {
ID ErrorID
DefaultMessage string // Used for Static errors or as fallback
IsSystem bool
Meta map[string]any // Default metadata to include
DefaultArgs []any
}
ErrorDefinition is the blueprint for creating errors
type ErrorGroup ¶
type ErrorGroup struct {
// contains filtered or unexported fields
}
ErrorGroup collects multiple errors thread-safely
func NewErrorGroup ¶
func NewErrorGroup(capacity int) *ErrorGroup
NewErrorGroup creates a new error group
func (*ErrorGroup) Add ¶
func (g *ErrorGroup) Add(err error) *ErrorGroup
Add adds an error to the group (nil-safe, concurrency-safe)
func (*ErrorGroup) Addf ¶
func (g *ErrorGroup) Addf(id ErrorID, format string, args ...interface{}) *ErrorGroup
Addf adds a formatted error string as a dynamic error (convenience method)
func (*ErrorGroup) Errors ¶
func (g *ErrorGroup) Errors() []*Error
Errors returns a copy of all collected errors (concurrency-safe)
func (*ErrorGroup) First ¶
func (g *ErrorGroup) First() *Error
First returns the first error or nil (concurrency-safe)
func (*ErrorGroup) HasErrors ¶
func (g *ErrorGroup) HasErrors() bool
HasErrors returns true if the group has any errors
func (*ErrorGroup) Last ¶
func (g *ErrorGroup) Last() *Error
Last returns the last error or nil (useful for "most recent error" scenarios)
func (*ErrorGroup) Len ¶
func (g *ErrorGroup) Len() int
Len returns the number of errors collected (concurrency-safe)
func (*ErrorGroup) Reset ¶
func (g *ErrorGroup) Reset() *ErrorGroup
Reset clears all errors (useful for pooling/reuse scenarios)
func (*ErrorGroup) ToError ¶
func (g *ErrorGroup) ToError() *Error
ToError converts the group to a single *Error Returns nil if no errors, the first error if only one, or a FailMultipleErrors error containing all errors in meta if multiple
func (*ErrorGroup) Unwrap ¶
func (g *ErrorGroup) Unwrap() []error
Unwrap implements the Go 1.20+ multiple error unwrapping interface This allows errors.Is() and errors.As() to check against any error in the group
type ErrorID ¶
type ErrorID struct {
// contains filtered or unexported fields
}
ErrorID represents a trusted, deterministically-generated error identifier IDs are generated from names using explicit numbering for stability across versions Static (S) and Dynamic (D) have separate counters within each domain Format: LEVEL_DOMAIN_NUM_TYPE (e.g., "0_AUTH_0042_S") Level indicates severity but does not affect uniqueness
func ID ¶
ID creates a new trusted ErrorID with explicit numbering This is the ONLY way to create a trusted ErrorID
WARNING: Must be called at package level (var declaration). Calling inside func init() or runtime functions causes unstable numbering. Use go:generate or static analysis to verify.
Parameters:
- name: Full error name (e.g., "AuthInvalidCredentials", "UserNotFound")
- domain: Error domain (e.g., "AUTH", "USER") - must be a prefix of the name
- static: true for static message, false for dynamic
- level: severity level (0-9 recommended)
- number: explicit number for this ID (must be unique within domain+type)
Panics if:
- Name doesn't start with domain
- Name already exists in registry
- Name is too similar to existing name (Levenshtein distance < 3)
- Domain is "FAIL" (reserved for internal errors)
- Number already used in this domain+type combination
Example:
var AuthInvalidCredentials = fail.ID(0, "AUTH", 0, true, "AuthInvalidCredentials") // 0_AUTH_0000_S
var AuthInvalidPassword = fail.ID(0, "AUTH", 1, true, "AuthInvalidPassword") // 0_AUTH_0001_S
var AuthCustomError = fail.ID(0, "AUTH", 0, false, "AuthCustomError") // 1_AUTH_0000_D
var AuthAnotherError = fail.ID(0, "AUTH", 1, false, "AuthAnotherError") // 0_AUTH_0001_D
// v0.0.2 - add new ID, gaps are fine
var AuthNewFeature = fail.ID("AuthNewFeature", "AUTH", true, 0, 100) // 0_AUTH_0100_S
func (ErrorID) IsTrusted ¶
IsTrusted returns true if this ID was created through the proper ID() function
type ErrorMatcher ¶
type ErrorMatcher struct {
// contains filtered or unexported fields
}
ErrorMatcher provides pattern matching on error IDs
func (*ErrorMatcher) Case ¶
func (m *ErrorMatcher) Case(id ErrorID, handler func(*Error)) *ErrorMatcher
Case checks if the error matches the given ID and executes the handler
func (*ErrorMatcher) CaseAny ¶
func (m *ErrorMatcher) CaseAny(handler func(*Error), ids ...ErrorID) *ErrorMatcher
func (*ErrorMatcher) CaseDomain ¶
func (m *ErrorMatcher) CaseDomain(handler func(*Error)) *ErrorMatcher
CaseDomain handles any domain error
func (*ErrorMatcher) CaseSystem ¶
func (m *ErrorMatcher) CaseSystem(handler func(*Error)) *ErrorMatcher
CaseSystem handles any system error
func (*ErrorMatcher) Default ¶
func (m *ErrorMatcher) Default(handler func(error))
Default handles any unmatched error
type ErrorType ¶
type ErrorType string
ErrorType indicates whether the error message is static or dynamic
type Frame ¶
type Frame struct {
Function string `json:"function"`
File string `json:"file"`
Line int `json:"line"`
Package string `json:"package,omitempty"`
}
Frame represents a single stack frame for error traces
type Hooks ¶
type Hooks struct {
OnMap []func(*Error, map[string]any)
// contains filtered or unexported fields
}
Hooks manages lifecycle callbacks for errors Access via Registry.Hooks
type IDRegistry ¶
type IDRegistry struct {
// contains filtered or unexported fields
}
IDRegistry manages error ID generation and validation Numbers are explicitly assigned per domain and type (static/dynamic)
func NewIDRegistry ¶
func NewIDRegistry() *IDRegistry
NewIDRegistry creates a new isolated ID registry (useful for testing or multi-app)
func (*IDRegistry) ExportIDList ¶
func (r *IDRegistry) ExportIDList() ([]byte, error)
ExportIDList returns all registered error IDs as JSON for this registry
func (*IDRegistry) GetAllIDs ¶
func (r *IDRegistry) GetAllIDs() []ErrorID
GetAllIDs returns all registered error IDs sorted by domain, type, then number
func (*IDRegistry) ID ¶
func (r *IDRegistry) ID(name, domain string, static bool, level, number int) ErrorID
ID creates a new trusted ErrorID for this registry
func (*IDRegistry) OverrideAllowRuntimePanics ¶ added in v1.1.11
func (r *IDRegistry) OverrideAllowRuntimePanics(allow bool)
OverrideAllowRuntimePanics sets per-registry override
func (*IDRegistry) Reset ¶
func (r *IDRegistry) Reset()
Reset clears all registered IDs (useful for testing)
func (*IDRegistry) ValidateIDs ¶
func (r *IDRegistry) ValidateIDs()
ValidateIDs checks for gaps and duplicates. Call in main() after all init().
type Mapper ¶
type Mapper interface {
Name() string
Priority() int
// Map attempts to map the input error to some other error (generic or fail)
// Returns ok = true if the mapper handled the error, false otherwise
Map(error) (error, bool)
// MapToFail : Optional convenience for mapping from generic error to fail.Error type
MapToFail(err error) (*Error, bool)
// MapFromFail : Optional convenience for mapping from fail.Error to another error type
MapFromFail(*Error) (error, bool)
}
Mapper converts errors in any direction: generic->fail, fail->generic, fail->fail, etc.
type MapperList ¶
type MapperList struct {
// contains filtered or unexported fields
}
MapperList keeps mappers sorted by priority using container/list
func NewMapperList ¶
func NewMapperList() *MapperList
NewMapperList creates a new MapperList. If includeDefault is true, adds the default mapper with priority -1
func (*MapperList) Add ¶
func (ml *MapperList) Add(m Mapper)
Add inserts a mapper into the list by descending priority
func (*MapperList) MapError ¶
func (ml *MapperList) MapError(err error) (error, bool)
MapError tries to map an error using mappers in priority order
func (*MapperList) MapFromFail ¶
func (ml *MapperList) MapFromFail(err *Error) (error, bool)
MapFromFail maps from *fail.Error
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds all registered error definitions and mappers
func NewRegistry ¶
NewRegistry creates a new isolated registry (for testing or multi-app scenarios)
func (*Registry) AllowInternalLogs ¶ added in v1.1.8
AllowInternalLogs enables or disables internal library logging for this registry. See AllowInternalLogs for details.
func (*Registry) AllowStaticMutations ¶ added in v1.1.10
AllowStaticMutations controls whether static errors in this registry can be mutated. When allow is false (default), builder methods on static errors return the original error unchanged. When allow is true shoudlPanic is ignored, mutations are permitted but may log warnings if internal logging is enabled.
If shouldPanic is true and allow is false, any builder method called on a static error will panic immediately with a descriptive message. This is useful for catching programming errors during development.
This method is safe for concurrent use.
func (*Registry) RegisterMany ¶
func (r *Registry) RegisterMany(defs ...*ErrorDefinition)
func (*Registry) RegisterMapper ¶
func (*Registry) RegisterTranslations ¶
RegisterTranslations adds translations for a locale in a specific registry
func (*Registry) RegisterTranslator ¶
func (r *Registry) RegisterTranslator(t Translator) error
func (*Registry) SetDefaultLocale ¶
SetDefaultLocale sets the fallback locale for the specific registry
type RetryConfig ¶
type RetryConfig struct {
MaxAttempts int
ShouldRetry func(error) bool
// Delay returns how long to wait BEFORE the next attempt.
// attempt starts at 1 for the first retry (not the first call).
Delay func(attempt int) time.Duration
}
RetryConfig helper for transient errors
type Tracer ¶
type Tracer interface {
Trace(operation string, fn func() error) error
TraceCtx(ctx context.Context, operation string, fn func(context.Context) error) error
}
Tracer allows users to provide their own tracing solution
type TranslationRegistry ¶
type TranslationRegistry struct {
// contains filtered or unexported fields
}
TranslationRegistry holds all translations
type Translator ¶
type Translator interface {
Name() string
// Supports reports whether this translator is allowed to translate this error.
// This is for capability, boundary, or policy checks — not mapping.
Supports(*Error) error
// Translate converts the error into an external representation.
// It may still fail even if Supports returned true (e.g. missing metadata).
Translate(*Error) (any, error)
}
Translator converts a trusted registry Error into another format (HTTP response, gRPC status, CLI output, etc.)
type ValidationError ¶
ValidationError represents a field validation error
func GetValidations ¶
func GetValidations(err error) ([]ValidationError, bool)
GetValidations extracts validation errors from an error