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 IsRegistered(err error) bool
- func IsRetryableDefault(err error) bool
- func IsStatic(err error) bool
- func IsSystem(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 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 RegisterLocalizations(locale string, msgs map[ErrorID]string)
- func RegisterMapper(mapper Mapper)
- 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 SetLocalizer(l Localizer)
- func SetLogger(logger Logger)
- func SetRetryConfig(config *RetryConfig)
- func SetTracer(tracer Tracer)
- func To(err *Error, translatorName string) (any, error)
- func ToAs[T any](err *Error, translatorName string) (T, error)
- func ToAsFrom[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 AsFail(err error) *Error
- 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 Record(e *Error) *Error
- func RecordCtx(ctx context.Context, e *Error) *Error
- func RegisterMany(defs ...*ErrorDefinition) *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) Clone() *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) FromGlobalRegistry() bool
- func (e *Error) FromRegistry(r *Registry) bool
- func (e *Error) GetLocalized() string
- func (e *Error) GetRegistry() *Registry
- func (e *Error) GetRendered() string
- func (e *Error) Internal(msg string) *Error
- func (e *Error) Internalf(format string, args ...any) *Error
- func (e *Error) IsRegistered() 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) Collect(err error)
- 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 ErrorType
- type Frame
- type HookType
- type Hooks
- type IDRegistry
- func (r *IDRegistry) ExportIDList() ([]byte, error)
- func (r *IDRegistry) GetAllIDs() []ErrorID
- func (r *IDRegistry) ID(level int, domain string, number int, static bool, name string) ErrorID
- func (r *IDRegistry) OverrideAllowRuntimePanics(allow bool)
- func (r *IDRegistry) Reset()
- func (r *IDRegistry) ValidateIDs()
- type Localizer
- 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) *Error
- func (r *Registry) RegisterLocalizations(locale string, msgs map[ErrorID]string)
- func (r *Registry) RegisterMany(defs ...*ErrorDefinition) *Error
- func (r *Registry) RegisterMapper(mapper Mapper)
- func (r *Registry) RegisterTranslator(t Translator) error
- func (r *Registry) SetDefaultLocale(locale string)
- func (r *Registry) SetLocalizer(l Localizer)
- func (r *Registry) SetLogger(logger Logger)
- func (r *Registry) SetTracer(tracer Tracer)
- func (r *Registry) To(err *Error, translatorName string) (zero any, retErr error)
- type RetryConfig
- type Tracer
- type Translator
- type UNSET
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
var ( UnregisteredError = internalID(0, 0, false, "FailUnregisteredError") TranslateUnregisteredError = internalID(0, 1, false, "FailTranslateUnregisteredError") TranslatorNotFound = internalID(0, 2, false, "FailTranslatorNotFound") TranslateUnsupportedError = internalID(0, 3, false, "FailTranslateUnsupportedError") TranslatePanicked = internalID(0, 4, false, "FailTranslatorPanicked") TranslateWrongType = internalID(0, 5, false, "FailTranslateWrongType") MultipleErrors = internalID(0, 6, false, "FailMultipleErrors") UnknownError = internalID(0, 7, false, "FailUnknownError") NotMatchedInAnyMapper = internalID(0, 8, false, "FailNotMatchedInAnyMapper") NoMapperRegistered = internalID(0, 9, false, "FailNoMapperRegistered") TranslatorAlreadyRegistered = internalID(0, 10, false, "FailTranslatorAlreadyRegistered") RuntimeIDInvalid = internalID(9, 11, false, "FailRuntimeIDInvalid") UnregisteredIDError = internalID(9, 12, false, "FailIDNotRegisteredError") RegisterManyError = internalID(9, 13, false, "FailRegisterManyError") RegistryAlreadyRegistered = internalID(9, 14, false, "FailRegistryAlreadyRegistered") TranslatorNil = internalID(0, 0, true, "FailTranslatorNil") TranslatorNameEmpty = internalID(0, 1, true, "FailTranslatorNameEmpty") )
IDs
Functions ¶
func AllowInternalLogs ¶
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 ¶
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 ¶
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 IsRegistered ¶
IsRegistered checks if a generic error is an Error and was registered to a registry
func IsRetryableDefault ¶
func MustRegisterTranslator ¶
func MustRegisterTranslator(t Translator)
func OnFromFail ¶
func OnFromFail(fn func(error))
func OnFromSuccess ¶
func OnTranslate ¶
func OverrideAllowIDRuntimePanics ¶
func OverrideAllowIDRuntimePanics(allow bool)
OverrideAllowIDRuntimePanics sets global id registry override
func OverrideAllowIDRuntimeRegistrationForTestingOnly ¶
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 RegisterLocalizations ¶ added in v3.1.0
RegisterLocalizations 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 SetLocalizer ¶ added in v3.1.0
func SetLocalizer(l Localizer)
SetLocalizer sets the global localization provider
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 global registry
func To ¶
To converts a fail.Error to an external format using the named translator Only registered errors can be translated (safety guarantee)
func ValidateIDs ¶
func ValidateIDs()
ValidateIDs checks for gaps and duplicates. Call in main() after all init().
Types ¶
type Error ¶
type Error struct {
// Required fields
// FIXME ID should be private to not let users perform 'surgery on errors'
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 AsFail ¶ added in v3.2.0
AsFail ensures the error is a *fail.Error. If err is already a *fail.Error, returns it as-is. If err is a generic error, converts via From() (uses mappers). If err is nil, returns nil.
This is useful at boundaries where you have generic errors but need *fail.Error for translation, hooks, or metadata access.
Example:
resp, _ := fail.To(fail.AsFail(err), "http")
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 RegisterMany ¶
func RegisterMany(defs ...*ErrorDefinition) *Error
RegisterMany registers multiple error definitions at once
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) FromGlobalRegistry ¶
FromGlobalRegistry checks if the Error is from the global Registry and return true or false accordingly
func (*Error) FromRegistry ¶
FromRegistry checks if the Error is from the passed in Registry and return true or false accordingly
func (*Error) GetLocalized ¶
GetLocalized returns the localized message template as string (read-only, no modification)
func (*Error) GetRegistry ¶
func (*Error) GetRendered ¶
GetRendered returns the fully rendered message as string (read-only, no modification)
func (*Error) IsRegistered ¶
IsRegistered checks if an error was registered to a registry
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) Collect ¶
func (g *ErrorGroup) Collect(err error)
Collect is the same as Add but without returning the error group
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.
CRITICAL: Since ErrorIDs are a global concept used throughout your entire codebase, they should ideally all be defined together in the same var block within a single package (e.g., a dedicated errors package). The default global registry cannot ensure uniqueness across packages and may incorrectly report gaps that don't actually exist due to Go's file compilation ordering. If IDs are scattered across multiple files/packages, the registry may see partial sequences and panic on apparent gaps that would be filled by later compilation units. Centralize all ID definitions in one location to ensure strict sequential numbering and avoid false gap detection.
NOTE: The global registry ALWAYS enforces strict sequential numbering (no gaps). If you need non-sequential numbering or want to disable gap checking, you must create your own isolated IDRegistry via NewIDRegistry() and use registry.ID() directly instead of this package-level ID() function. Custom registries allow you to control gap checking behavior, but the global registry is strict by design to ensure consistency across the entire codebase.
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
- Any gap in numbering is detected that is not being filled by current insertion
Example:
// Centralized in one package - RECOMMENDED
var (
AuthInvalidCredentials = fail.ID(0, "AUTH", 0, true, "AuthInvalidCredentials") // 0_AUTH_0000_S
AuthInvalidPassword = fail.ID(0, "AUTH", 1, true, "AuthInvalidPassword") // 0_AUTH_0001_S
AuthCustomError = fail.ID(0, "AUTH", 0, false, "AuthCustomError") // 0_AUTH_0000_D
AuthAnotherError = fail.ID(0, "AUTH", 1, false, "AuthAnotherError") // 0_AUTH_0001_D
// v0.0.2 - add new ID, must be next in sequence
AuthNewFeature = fail.ID(0, "AUTH", 2, true, "AuthNewFeature") // 0_AUTH_0002_S
)
func (ErrorID) IsRegistered ¶
IsRegistered returns true if this ID was created through the proper ID() function
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) OverrideAllowRuntimePanics ¶
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 Localizer ¶ added in v3.1.0
type Localizer interface {
// Localize returns the localized template for the given error ID and locale
// Returns empty string if no translation exists
Localize(id ErrorID, locale string) string
// RegisterLocalization adds a single translation (for AddLocalization)
RegisterLocalization(id ErrorID, locale string, template string)
// RegisterLocalizations adds multiple translations for a locale (for bulk operations)
RegisterLocalizations(locale string, translations map[ErrorID]string)
}
type Mapper ¶
type Mapper interface {
Name() string
Priority() int
// Map : should map generic errors to fail.Error type
Map(err error) (*Error, bool)
}
Mapper converts errors in any direction: generic->fail, fail->generic, fail->fail, etc.
IMPORTANT: Map must return errors created via fail.New() or fail.From(), not hand-crafted *fail.Error structs. Hand-crafted errors will be unregistered and may cause issues with translators and other components that require registered errors.
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
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds all registered error definitions and mappers
func MustNewRegistry ¶
MustNewRegistry creates a new isolated registry (for testing or multi-app scenarios) Panics if a registry of the same name is already registered
func NewRegistry ¶
NewRegistry creates a new isolated registry (for testing or multi-app scenarios)
func (*Registry) AllowInternalLogs ¶
AllowInternalLogs enables or disables internal library logging for this registry. See AllowInternalLogs for details.
func (*Registry) AllowStaticMutations ¶
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) RegisterLocalizations ¶ added in v3.1.0
RegisterLocalizations adds translations for a locale in a specific registry
func (*Registry) RegisterMany ¶
func (r *Registry) RegisterMany(defs ...*ErrorDefinition) *Error
func (*Registry) RegisterMapper ¶
func (*Registry) RegisterTranslator ¶
func (r *Registry) RegisterTranslator(t Translator) error
func (*Registry) SetDefaultLocale ¶
SetDefaultLocale sets the fallback locale for the specific registry
func (*Registry) SetLocalizer ¶ added in v3.1.0
SetLocalizer sets the localization provider for this 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 {
// Record records an error occurrence (simple version)
Record(err *Error) *Error
// RecordCtx records an error with context (for spans, baggage, etc.)
RecordCtx(ctx context.Context, err *Error) *Error
}
Tracer allows users to provide their own tracing solution
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
func NewValidationError ¶ added in v3.2.0
func NewValidationError(field, msg string) ValidationError
NewValidationError is a helper for initializing a validation error