Documentation
¶
Overview ¶
Package errors provides a robust error handling library with support for error wrapping, stack traces, context storage, and retry mechanisms. It extends the standard library's error interface with features like HTTP-like status codes, error categorization, and JSON serialization, while maintaining compatibility with `errors.Is`, `errors.As`, and `errors.Unwrap`. The package is thread-safe and optimized with object pooling for performance.
Package errors provides utilities for error handling, including a flexible retry mechanism.
Index ¶
- Constants
- Variables
- func As(err error, target interface{}) bool
- func AsType[T error](err error) (T, bool)
- func Caller(skip int) (file string, line int, function string)
- func Category(err error) string
- func Code(err error) int
- func Collect(ctx context.Context, ch <-chan error, n int) error
- func Configure(cfg Config)
- func Contains(err error, targets ...error) bool
- func Context(err error) map[string]interface{}
- func Count(err error) uint64
- func Drain(ch <-chan error) error
- func ExecuteReply[T any](r *Retry, fn func() (T, error)) (T, error)
- func Fan(ctx context.Context, chans ...<-chan error) <-chan error
- func Filter[T error](err error) []T
- func Find(err error, pred func(error) bool) error
- func FindType[T error](err error, predicate func(T) bool) (T, bool)
- func First(ctx context.Context, ch <-chan error) error
- func FirstOfType[T error](err error) (T, bool)
- func FmtErrorCheck(format string, args ...interface{}) (result string, err error)
- func FormatError(err error) string
- func HTTPError(w http.ResponseWriter, err error, opts ...HTTPOption)
- func HTTPStatusCode(err error, defaultCode int) int
- func Has(err error) bool
- func HasContextKey(err error, key string) bool
- func Inspect(err error, targets ...interface{})
- func InspectError(err *Error, targets ...interface{})
- func Is(err, target error) bool
- func IsEmpty(err error) bool
- func IsError(err error) bool
- func IsNull(err error) bool
- func IsRetryable(err error) bool
- func IsTimeout(err error) bool
- func IsType[T error](err error) bool
- func Join(errs ...error) error
- func JoinErrors(errs []error, keyValues ...interface{}) error
- func Map[T error, R any](err error, fn func(T) R) []R
- func Name(err error) string
- func Reduce[T error, R any](err error, initial R, fn func(T, R) R) R
- func Stack(err error) []string
- func Std(text string) error
- func Stdf(format string, a ...interface{}) error
- func Unwrap(err error) error
- func UnwrapAll(err error) []error
- func Walk(err error, fn func(error))
- func WarmPool(count int)
- func WarmStackPool(count int)
- func With(err error, key string, value interface{}) error
- type BackoffStrategy
- type Chain
- func (c *Chain) Call(fn interface{}, args ...interface{}) *Chain
- func (c *Chain) Code(code int) *Chain
- func (c *Chain) Errors() []error
- func (c *Chain) HasErrors() bool
- func (c *Chain) LastError() error
- func (c *Chain) Len() int
- func (c *Chain) LogOnFail() *Chain
- func (c *Chain) MaxErrors(max int) *Chain
- func (c *Chain) Optional() *Chain
- func (c *Chain) Reset()
- func (c *Chain) Retry(maxAttempts int, delay time.Duration, opts ...RetryOption) *Chain
- func (c *Chain) Run() error
- func (c *Chain) RunAll() error
- func (c *Chain) Step(fn func() error) *Chain
- func (c *Chain) StepCtx(fn func(ctx context.Context) error) *Chain
- func (c *Chain) Tag(category ErrorCategory) *Chain
- func (c *Chain) Timeout(d time.Duration) *Chain
- func (c *Chain) Unwrap() []error
- func (c *Chain) With(key string, value interface{}) *Chain
- func (c *Chain) WithLog(attrs ...slog.Attr) *Chain
- type ChainOption
- type Config
- type ConstantBackoff
- type Error
- func Convert(err error) *Error
- func Empty() *Error
- func Err(msg string, err error) *Error
- func Errorf(format string, args ...interface{}) *Error
- func From(err error) *Error
- func FromContext(ctx context.Context, err error) *Error
- func Merge(errs ...error) *Error
- func Named(name string) *Error
- func New(text string) *Error
- func Newf(f any, args ...interface{}) *Error
- func Trace(text string) *Error
- func Tracef(format string, args ...interface{}) *Error
- func Transform(err error, fn func(*Error)) *Error
- func WithStack(err error) *Error
- func Wrap(err error, wrapper *Error) *Error
- func Wrapf(err error, format string, args ...interface{}) *Error
- func (e *Error) As(target interface{}) bool
- func (e *Error) Callback(fn func()) *Error
- func (e *Error) Category() string
- func (e *Error) Code() int
- func (e *Error) Context() map[string]interface{}
- func (e *Error) Copy() *Error
- func (e *Error) Count() uint64
- func (e *Error) Err() error
- func (e *Error) Error() string
- func (e *Error) FastStack() []string
- func (e *Error) Find(pred func(error) bool) error
- func (e *Error) Format() string
- func (e *Error) Free()
- func (e *Error) Has() bool
- func (e *Error) HasContextKey(key string) bool
- func (e *Error) Increment() *Error
- func (e *Error) Is(target error) bool
- func (e *Error) IsEmpty() bool
- func (e *Error) IsNull() bool
- func (e *Error) LogValue() slog.Value
- func (e *Error) MarshalJSON() ([]byte, error)
- func (e *Error) Msgf(format string, args ...interface{}) *Error
- func (e *Error) Name() string
- func (e *Error) Reset()
- func (e *Error) Stack() []string
- func (e *Error) Trace() *Error
- func (e *Error) Transform(fn func(*Error)) *Error
- func (e *Error) Unwrap() error
- func (e *Error) UnwrapAll() []error
- func (e *Error) Walk(fn func(error))
- func (e *Error) With(keyValues ...interface{}) *Error
- func (e *Error) WithCategory(category ErrorCategory) *Error
- func (e *Error) WithCode(code int) *Error
- func (e *Error) WithName(name string) *Error
- func (e *Error) WithRetryable() *Error
- func (e *Error) WithStack() *Error
- func (e *Error) WithTemplate(template string) *Error
- func (e *Error) WithTimeout() *Error
- func (e *Error) Wrap(cause error) *Error
- func (e *Error) WrapNotNil(cause error) *Error
- func (e *Error) Wrapf(cause error, format string, args ...interface{}) *Error
- type ErrorCategory
- type ErrorFormatter
- type ErrorOpts
- type ErrorPool
- type ExponentialBackoff
- type Group
- type GroupOption
- type HTTPOption
- type InspectOption
- type LinearBackoff
- type MultiError
- func (m *MultiError) Add(errs ...error)
- func (m *MultiError) Addf(format string, args ...interface{})
- func (m *MultiError) Clear()
- func (m *MultiError) Count() int
- func (m *MultiError) Error() string
- func (m *MultiError) Errors() []error
- func (m *MultiError) Filter(fn func(error) bool) *MultiError
- func (m *MultiError) First() error
- func (m *MultiError) Has() bool
- func (m *MultiError) IsNull() bool
- func (m *MultiError) Last() error
- func (m *MultiError) MarshalJSON() ([]byte, error)
- func (m *MultiError) Merge(other *MultiError)
- func (m *MultiError) Single() error
- func (m *MultiError) String() string
- func (m *MultiError) Unwrap() []error
- type MultiErrorOption
- type Retry
- type RetryOption
- func WithBackoff(strategy BackoffStrategy) RetryOption
- func WithContext(ctx context.Context) RetryOption
- func WithDelay(delay time.Duration) RetryOption
- func WithJitter(jitter bool) RetryOption
- func WithMaxAttempts(maxAttempts int) RetryOption
- func WithMaxDelay(maxDelay time.Duration) RetryOption
- func WithOnRetry(onRetry func(attempt int, err error)) RetryOption
- func WithRetryIf(retryIf func(error) bool) RetryOption
- type Sentinel
- func (s *Sentinel) As(target any) bool
- func (s *Sentinel) Error() string
- func (s *Sentinel) Is(target error) bool
- func (s *Sentinel) LogValue() slog.Value
- func (s *Sentinel) MarshalJSON() ([]byte, error)
- func (s *Sentinel) Name() string
- func (s *Sentinel) String() string
- func (s *Sentinel) Unwrap() error
- func (s *Sentinel) With(msg string) *Error
- type Stream
Constants ¶
const (
DefaultCode = 500 // Default HTTP status code for errors if not specified.
)
Constants defining default configuration and context keys.
Variables ¶
var ErrLimitReached = Const("limit_reached", "error collection limit reached")
ErrLimitReached is returned by Collect when n errors have been gathered before the channel closed or the context was done. Callers can use errors.Is(err, ErrLimitReached) to distinguish this case.
Functions ¶
func As ¶
As wraps errors.As, using custom type assertion for *Error types. Falls back to standard errors.As for non-*Error types. Returns false if either err or target is nil.
func AsType ¶ added in v1.3.0
AsType attempts to find the first error in the chain that matches type T. Returns the matched error and true if found, otherwise zero value and false.
func Caller ¶
Caller returns the file, line, and function name of the caller at skip level. Skip=0 returns the caller of this function, 1 returns its caller, etc.
func Category ¶
Category returns the category of an error, if it is an *Error. Returns an empty string for non-*Error types or unset categories.
func Code ¶
Code returns the status code of an error, if it is an *Error. Returns 500 as a default for non-*Error types to indicate an internal error.
func Collect ¶ added in v1.3.0
Collect reads up to n non-nil errors from ch (or until ch closes or ctx is done) and returns them as a *MultiError.
If the limit n is reached before the channel closes, the returned error wraps ErrLimitReached as its cause so callers can distinguish the two cases:
err := errors.Collect(ctx, errs, 10)
if errors.Is(err, errors.ErrLimitReached) {
// stopped early — more errors may exist
}
func Configure ¶
func Configure(cfg Config)
Configure updates the global configuration for the errors package. It is thread-safe and should be called early to avoid race conditions. Changes apply to all subsequent error operations. Example:
errors.Configure(errors.Config{StackDepth: 16, DisablePooling: true})
func Contains ¶ added in v1.3.0
Contains checks if any error in the chain matches any of the target errors. Uses our package's Is function for matching.
func Context ¶
Context extracts the context map from an error, if it is an *Error. Returns nil for non-*Error types or if no context is present.
func Count ¶
Count returns the occurrence count of an error, if it is an *Error. Returns 0 for non-*Error types.
func Drain ¶ added in v1.3.0
Drain reads all errors from ch until it is closed and returns them as a *MultiError. Returns nil if every received value was nil. Blocks until ch is closed.
Example:
results, errs := processItems(ctx, items)
if err := errors.Drain(errs); err != nil {
log.Println(err)
}
func ExecuteReply ¶
ExecuteReply runs the provided function with retry logic and returns its result. Returns the result and nil on success, or zero value and last error on failure; generic type T.
func Fan ¶ added in v1.3.0
Fan merges multiple error channels into a single output channel that closes when all inputs have closed or ctx is done.
Callers MUST either drain the returned channel to completion OR cancel ctx — failing to do so leaks the internal goroutines. The select in each forwarder respects ctx.Done() so cancellation is always safe.
Example:
errs1, errs2 := stage1(ctx), stage2(ctx)
for err := range errors.Fan(ctx, errs1, errs2) {
if err != nil { log.Println(err) }
}
func Find ¶
Find searches the error chain for the first error matching pred. Returns nil if no match is found or pred is nil; traverses both Unwrap() and Cause() chains.
func FindType ¶ added in v1.3.0
FindType returns the first error in the chain of type T that satisfies the predicate.
func First ¶ added in v1.3.0
First returns the first non-nil error received from ch, then returns. Uses ctx for deadline/cancellation only — it does NOT call any cancel function. The caller is responsible for cancelling sibling work after First returns.
Returns nil if ch is closed before any error arrives, or ctx is done. Returns ctx.Err() if the context is cancelled or times out.
Example:
ctx, cancel := context.WithCancel(context.Background())
results, errs := processItems(ctx, items)
if err := errors.First(ctx, errs); err != nil {
cancel() // caller decides to stop siblings
log.Println(err)
}
defer cancel()
func FirstOfType ¶ added in v1.3.0
FirstOfType returns the first error in the chain of type T.
func FmtErrorCheck ¶
FmtErrorCheck safely formats a string using fmt.Sprintf, catching panics. Returns the formatted string and any error encountered. Internal use by Newf to validate format strings. Example:
result, err := FmtErrorCheck("value: %s", "test")
func FormatError ¶
FormatError returns a formatted string representation of an error.
func HTTPError ¶ added in v1.3.0
func HTTPError(w http.ResponseWriter, err error, opts ...HTTPOption)
HTTPError writes err to w as an HTTP error response.
Status code resolution (first match wins): err is *Error with Code() in the valid HTTP range (100–599) WithFallbackCode option (default 500)
Content-Type defaults to text/plain unless WithBodyFunc provides content that implies a different type (caller must set the header themselves in that case — use WithBodyFunc + manual header setting).
Example — simplest usage, plain text body, 500 fallback:
errors.HTTPError(w, err)
Example — custom fallback status:
errors.HTTPError(w, err, errors.WithFallbackCode(http.StatusBadGateway))
Example — suppress body (header only):
errors.HTTPError(w, err, errors.WithBody(false))
Example — JSON body:
errors.HTTPError(w, err,
errors.WithBodyFunc(func(e error) string {
return fmt.Sprintf(`{"error":%q,"code":%d}`,
e.Error(), errors.HTTPStatusCode(e, 500))
}),
)
func HTTPStatusCode ¶ added in v1.3.0
HTTPStatusCode returns the HTTP status code embedded in err. If err is nil, has no code, or the code is outside the valid HTTP range (100–599), defaultCode is returned.
Example:
status := errors.HTTPStatusCode(err, http.StatusInternalServerError)
func Has ¶
Has checks if an error contains meaningful content. Returns true for non-nil standard errors or *Error with content (msg, name, template, or cause).
func HasContextKey ¶
HasContextKey checks if the error's context contains the specified key. Returns false for non-*Error types or if the key is not present in the context.
func Inspect ¶
func Inspect(err error, targets ...interface{})
Inspect writes a human-readable description of err to each writer in ws. If no writers are supplied it defaults to os.Stderr. Multiple writers are combined with io.MultiWriter so a single call can write to a log file and a buffer simultaneously.
Example — default (stderr):
errors.Inspect(err)
Example — write to a buffer for testing:
var buf bytes.Buffer errors.Inspect(err, &buf)
Example — write to both stderr and a file:
errors.Inspect(err, os.Stderr, logFile)
Example — customise stack depth:
errors.Inspect(err, os.Stderr, errors.WithStackFrames(5))
Note: InspectOption values must come after all io.Writer values. Any value that is neither an io.Writer nor an InspectOption is silently ignored.
func InspectError ¶
func InspectError(err *Error, targets ...interface{})
InspectError is a convenience wrapper for *Error that calls Inspect. Kept for backwards compatibility; prefer Inspect for new code.
func Is ¶
Is wraps errors.Is, using custom matching for *Error types. Falls back to standard errors.Is for non-*Error types; returns true if err equals target.
func IsEmpty ¶
IsEmpty checks if an error has no meaningful content. Returns true for nil errors, empty *Error instances, or standard errors with whitespace-only messages.
func IsError ¶
IsError checks if an error is an instance of *Error. Returns true only for this package's custom error type; false for nil or other types.
func IsNull ¶
IsNull checks if an error is nil or represents a NULL value. Delegates to *Error’s IsNull for custom errors; uses sqlNull for others.
func IsRetryable ¶
IsRetryable checks if an error is retryable. For *Error, checks context for retry flag; for others, looks for "retry" or timeout in message. Returns false for nil errors; thread-safe for *Error types.
func IsTimeout ¶
IsTimeout checks if an error indicates a timeout. For *Error, checks context for timeout flag; for others, looks for "timeout" in message. Returns false for nil errors.
func Join ¶ added in v1.3.0
Join returns an error that wraps the given errors. Any nil error values are discarded. Join returns nil if every error is nil. The error formats as the concatenation of the errors' strings, separated by newlines. The resulting error implements Unwrap() []error if multiple non-nil errors are present.
func JoinErrors ¶ added in v1.3.0
JoinErrors joins multiple errors using Join and wraps them with context. Returns nil if all errors are nil.
func Map ¶ added in v1.3.0
Map applies a transformation function to each error of type T in the chain.
func Name ¶
Name returns the name of an error, if it is an *Error. Returns an empty string for non-*Error types or unset names.
func Reduce ¶ added in v1.3.0
Reduce walks the error chain and accumulates a result for errors of type T.
func Stack ¶
Stack extracts the stack trace from an error, if it is an *Error. Returns nil for non-*Error types or if no stack is present.
func Std ¶
Std creates a standard error using errors.New for compatibility. Does not capture stack traces or add context. Example:
err := errors.Std("simple error")
func Stdf ¶
Stdf creates a formatted standard error using fmt.Errorf for compatibility. Supports %w for wrapping; does not capture stack traces. Example:
err := errors.Stdf("failed: %w", cause)
func Unwrap ¶
Unwrap returns the underlying cause of an error, if it implements Unwrap. For *Error, returns cause; for others, returns the error itself; nil if err is nil.
func UnwrapAll ¶
UnwrapAll returns a slice of all errors in the chain, including the root error. Traverses both Unwrap() and Cause() chains; returns nil if err is nil.
func Walk ¶
Walk traverses the error chain, applying fn to each error. Supports both Unwrap() and Cause() interfaces; stops at nil or non-unwrappable errors.
func WarmPool ¶
func WarmPool(count int)
WarmPool pre-populates the error pool with count instances. Improves performance by reducing initial allocations. No-op if pooling is disabled. Example:
errors.WarmPool(1000)
func WarmStackPool ¶
func WarmStackPool(count int)
WarmStackPool pre-populates the stack pool with count slices. Improves performance for stack-intensive operations. No-op if pooling is disabled. Example:
errors.WarmStackPool(500)
Types ¶
type BackoffStrategy ¶
type BackoffStrategy interface {
// Backoff returns the delay for a given attempt based on the base delay.
Backoff(attempt int, baseDelay time.Duration) time.Duration
}
BackoffStrategy defines the interface for calculating retry delays.
type Chain ¶
type Chain struct {
// contains filtered or unexported fields
}
Chain executes functions sequentially with enhanced error handling. Logging is optional and configured via a slog.Handler.
func NewChain ¶
func NewChain(opts ...ChainOption) *Chain
NewChain creates a new Chain with the given options. Logging is disabled by default (logHandler is nil).
func (*Chain) Call ¶
Call adds a step by wrapping a function with arguments. It uses reflection to validate and invoke the function.
func (*Chain) Optional ¶
Optional marks the last step as optional. Optional steps don't stop the chain on error.
func (*Chain) Retry ¶
Retry configures retry behavior for the last step. Retry configures retry behavior for the last step.
func (*Chain) Run ¶
Run executes the chain, stopping on the first non-optional error. It returns the first error encountered or nil if all steps succeed.
func (*Chain) RunAll ¶
RunAll executes all steps, collecting errors without stopping. It returns a MultiError containing all errors or nil if none occurred.
func (*Chain) Step ¶
Step adds a new step to the chain with the provided function. The function must return an error or nil.
func (*Chain) StepCtx ¶ added in v1.3.0
StepCtx adds a context-aware step to the chain. The provided function receives the chain's context (which carries any chain-level deadline/timeout), so cancellation and timeouts propagate correctly into blocking operations such as HTTP requests, database queries, or gRPC calls.
StepCtx is the context-safe alternative to Step; existing Step calls are unchanged and fully compatible.
Example:
chain := NewChain(ChainWithTimeout(5 * time.Second)).
StepCtx(func(ctx context.Context) error {
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
_, err := http.DefaultClient.Do(req)
return err
})
func (*Chain) Tag ¶
func (c *Chain) Tag(category ErrorCategory) *Chain
Tag sets an error category for the last step.
func (*Chain) Timeout ¶
Timeout sets a timeout for the entire chain. Thread-safe: protected by configMu.
type ChainOption ¶
type ChainOption func(*Chain)
ChainOption defines a function that configures a Chain.
func ChainWithAutoWrap ¶
func ChainWithAutoWrap(auto bool) ChainOption
ChainWithAutoWrap enables or disables automatic error wrapping.
func ChainWithLogHandler ¶
func ChainWithLogHandler(handler slog.Handler) ChainOption
ChainWithLogHandler sets a custom slog.Handler for logging. If handler is nil, logging is effectively disabled.
func ChainWithMaxErrors ¶
func ChainWithMaxErrors(max int) ChainOption
ChainWithMaxErrors sets the maximum number of errors allowed. A value <= 0 means no limit.
func ChainWithTimeout ¶
func ChainWithTimeout(d time.Duration) ChainOption
ChainWithTimeout sets a timeout for the entire chain.
type Config ¶
type Config struct {
StackDepth int // Maximum stack trace depth; 0 uses default (32).
ContextSize int // Initial context map size; 0 uses default (4).
DisablePooling bool // If true, disables object pooling for errors.
FilterInternal bool // If true, filters internal package frames from stack traces.
AutoFree bool // If true, automatically returns errors to pool when GC collects them.
}
Config defines the global configuration for the errors package, controlling stack depth, context size, pooling, and frame filtering.
type ConstantBackoff ¶
type ConstantBackoff struct{}
ConstantBackoff provides a fixed delay for each retry attempt.
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
Error is a custom error type with enhanced features: message, name, stack trace, context, cause, and metadata like code and category. It is thread-safe and supports pooling for performance.
func Convert ¶
Convert transforms any error into an *Error, preserving its message and wrapping it if needed. Returns nil if the input is nil; returns the original if already an *Error. Uses multiple strategies: direct assertion, errors.As, manual unwrapping, and fallback creation.
func Empty ¶
func Empty() *Error
Empty returns a new empty error with no message, name, or stack trace. Useful for incrementally building errors or as a neutral base. Example:
err := errors.Empty().With("key", "value").WithCode(400)
func Err ¶ added in v1.2.0
Err creates a new Error with the given message and wraps the provided error as its cause.
func From ¶
From transforms any error into an *Error, preserving its message and wrapping it if needed. Alias of Convert; returns nil if input is nil, original if already an *Error.
func FromContext ¶
FromContext creates an *Error from a context and an existing error. Enhances the error with context info: timeout status, deadline, or cancellation. Returns nil if input error is nil; does not store context values directly.
func Merge ¶
Merge combines multiple errors into a single *Error. Aggregates messages with "; " separator, merges contexts and stacks; returns nil if no errors provided.
func Named ¶
Named creates an error with the specified name and captures a stack trace. The name doubles as the error message if no message is set. Use for errors where type identification and stack context are important. Example:
err := errors.Named("AuthError").WithCode(401)
func New ¶
New creates a lightweight error with the given message and no stack trace. Optimized for performance; use Trace() for stack traces. Returns a shared empty error for empty messages to reduce allocations. Example:
err := errors.New("invalid input")
func Newf ¶
Newf creates a formatted error, supporting the %w verb for wrapping errors. If the format contains exactly one %w verb with a non-nil error argument, the error is wrapped as the cause. The final error message string generated by Error() will be compatible with the output of fmt.Errorf for the same inputs. Does not capture a stack trace by default. Example:
cause := errors.New("db error")
err := errors.Newf("query failed: %w", cause)
// err.Error() will match fmt.Errorf("query failed: %w", cause).Error()
// errors.Unwrap(err) == cause
func Trace ¶
Trace creates an error with the given message and captures a stack trace. Use when debugging context is needed; for performance, prefer New(). Example:
err := errors.Trace("operation failed")
func Tracef ¶
Tracef creates a formatted error with a stack trace. Supports %w for wrapping errors. Example:
err := errors.Tracef("query %s failed: %w", query, cause)
func Transform ¶
Transform applies transformations to an error, returning a new *Error. Creates a new *Error from non-*Error types before applying fn; returns nil if err is nil.
func WithStack ¶
WithStack converts any error to an *Error and captures a stack trace. Returns nil if input is nil; adds stack to existing *Error or wraps non-*Error types.
func Wrap ¶
Wrap creates a new *Error that wraps another error with additional context. Uses a copy of the provided wrapper *Error; returns nil if err is nil.
func Wrapf ¶
Wrapf creates a new formatted *Error that wraps another error. Formats the message and sets the cause; returns nil if err is nil.
func (*Error) As ¶
As attempts to assign the error or one in its chain to the target interface. Supports *Error and standard error types, traversing the cause chain. Returns true if successful. Example:
var target *Error
if errors.As(err, &target) {
fmt.Println(target.Name())
}
func (*Error) Callback ¶
Callback sets a function to be called when Error() is invoked. Useful for logging or side effects on error access. Example:
err := errors.New("test").Callback(func() { log.Println("error accessed") })
func (*Error) Category ¶
Category returns the error’s category, if set. Example:
if err.Category() == "network" {
handleNetworkError(err)
}
func (*Error) Code ¶
Code returns the error’s HTTP-like status code, if set. Returns 0 if no code is set. Example:
if err.Code() == 404 {
renderNotFound()
}
func (*Error) Context ¶
Context returns the error’s context as a map, merging smallContext and map-based context. Thread-safe; lazily initializes the map if needed. Example:
ctx := err.Context()
if userID, ok := ctx["user_id"]; ok {
fmt.Println(userID)
}
func (*Error) Copy ¶
Copy creates a deep copy of the error, preserving all fields except stack freshness. The new error can be modified independently. Example:
newErr := err.Copy().With("new_key", "value")
func (*Error) Count ¶
Count returns the number of times the error has been incremented. Useful for tracking error frequency. Example:
fmt.Printf("Error occurred %d times", err.Count())
func (*Error) Err ¶
Err returns the error as an error interface. Useful for type assertions or interface compatibility. Example:
var stdErr error = err.Err()
func (*Error) Error ¶
Error returns the string representation of the error. If the error was created using Newf/Errorf with the %w verb, it returns the pre-formatted string compatible with fmt.Errorf. Otherwise, it combines the message, template, or name with the cause's error string, separated by ": ". Invokes any set callback.
func (*Error) FastStack ¶
FastStack returns a lightweight stack trace with file and line numbers only. Omits function names for performance; skips internal frames if configured. Returns nil if no stack trace exists. Example:
for _, frame := range err.FastStack() {
fmt.Println(frame) // e.g., "main.go:42"
}
func (*Error) Find ¶
Find searches the error chain for the first error where pred returns true. Returns nil if no match is found or if pred is nil. Example:
err := err.Find(func(e error) bool { return strings.Contains(e.Error(), "timeout") })
func (*Error) Format ¶
Format returns a detailed, human-readable string representation of the error, including message, code, context, stack, and cause. Recursive for causes that are also *Error. Example:
fmt.Println(err.Format()) // Output: // Error: failed: cause // Code: 500 // Context: // key: value // Stack: // 1. main.main main.go:42
func (*Error) Free ¶
func (e *Error) Free()
Free resets the error and returns it to the pool if pooling is enabled. Safe to call multiple times; no-op if pooling is disabled. Call after use to return the error to the pool and prevent memory leaks. Use defer err.Free() at the call site that created the error. Example:
defer err.Free()
func (*Error) Has ¶
Has checks if the error contains meaningful content (message, template, name, or cause). Returns false for nil or empty errors. Example:
if !err.Has() {
return nil
}
func (*Error) HasContextKey ¶
HasContextKey checks if the specified key exists in the error’s context. Thread-safe; checks both smallContext and map-based context. Example:
if err.HasContextKey("user_id") {
fmt.Println(err.Context()["user_id"])
}
func (*Error) Increment ¶
Increment atomically increases the error’s count by 1 and returns the error. Useful for tracking repeated occurrences. Example:
err := err.Increment()
func (*Error) Is ¶
Is checks if the error matches the target by pointer, name, or cause chain. Compatible with errors.Is; also matches by string for standard errors. Returns true if the error or its cause matches the target. Example:
if errors.Is(err, errors.New("target")) {
handleTargetError()
}
func (*Error) IsEmpty ¶
IsEmpty checks if the error lacks meaningful content (no message, name, template, or cause). Returns true for nil or fully empty errors. Example:
if err.IsEmpty() {
return nil
}
func (*Error) IsNull ¶
IsNull checks if the error is nil, empty, or contains only SQL NULL values in its context or cause. Useful for handling database-related errors. Example:
if err.IsNull() {
return nil
}
func (*Error) LogValue ¶ added in v1.3.0
LogValue implements slog.LogValuer so *Error can be passed directly to any slog logging call and will be rendered as a structured group containing message, name, code, category, and context fields.
Example:
slog.Error("request failed", "err", err)
// => err.message="...", err.name="AuthError", err.code=401, ...
func (*Error) MarshalJSON ¶
MarshalJSON serializes the error to JSON, including name, message, context, cause, stack, and code. Causes are recursively serialized if they implement json.Marshaler or are *Error. Example:
data, _ := json.Marshal(err) fmt.Println(string(data))
func (*Error) Msgf ¶
Msgf sets the error’s message using a formatted string and returns the error. Overwrites any existing message. Example:
err := err.Msgf("user %s not found", username)
func (*Error) Name ¶
Name returns the error’s name, if set. Example:
if err.Name() == "AuthError" {
handleAuthError()
}
func (*Error) Reset ¶
func (e *Error) Reset()
Reset clears all fields of the error, preparing it for reuse in the pool. Internal use by Free; does not release stack to stackPool. Example:
err.Reset() // Clear all fields.
func (*Error) Stack ¶
Stack returns a detailed stack trace with function names, files, and line numbers. Filters internal frames if configured; returns nil if no stack exists. Example:
for _, frame := range err.Stack() {
fmt.Println(frame) // e.g., "main.main main.go:42"
}
func (*Error) Trace ¶
Trace ensures the error has a stack trace, capturing it if absent. Returns the error for chaining. Example:
err := errors.New("failed").Trace()
func (*Error) Transform ¶
Transform applies transformations to a copy of the error and returns the new error. The original error is unchanged; nil-safe. Example:
newErr := err.Transform(func(e *Error) { e.With("key", "value") })
func (*Error) Unwrap ¶
Unwrap returns the underlying cause of the error, if any. Compatible with errors.Unwrap for chain traversal. Example:
cause := errors.Unwrap(err)
func (*Error) UnwrapAll ¶
UnwrapAll returns a slice of all errors in the chain, starting with this error. Each error is isolated to prevent modifications affecting others. Example:
chain := err.UnwrapAll()
for _, e := range chain {
fmt.Println(e.Error())
}
func (*Error) Walk ¶
Walk traverses the error chain, applying fn to each error. Stops if fn is nil or the chain ends. Example:
err.Walk(func(e error) { fmt.Println(e.Error()) })
func (*Error) With ¶
With adds key-value pairs to the error's context and returns the error. Uses a fixed-size array (smallContext) for up to contextSize items, then switches to a map. Thread-safe. Accepts variadic key-value pairs. Example:
err := err.With("key1", value1, "key2", value2)
func (*Error) WithCategory ¶
func (e *Error) WithCategory(category ErrorCategory) *Error
WithCategory sets the error’s category and returns the error. Example:
err := err.WithCategory("validation")
func (*Error) WithCode ¶
WithCode sets an HTTP-like status code and returns the error. Example:
err := err.WithCode(400)
func (*Error) WithName ¶
WithName sets the error’s name and returns the error. Example:
err := err.WithName("AuthError")
func (*Error) WithRetryable ¶
WithRetryable marks the error as retryable in its context and returns the error. Example:
err := err.WithRetryable()
func (*Error) WithStack ¶
WithStack captures a stack trace if none exists and returns the error. Skips one frame (caller of WithStack). Example:
err := errors.New("failed").WithStack()
func (*Error) WithTemplate ¶
WithTemplate sets a message template and returns the error. Used as a fallback if the message is empty. Example:
err := err.WithTemplate("operation failed")
func (*Error) WithTimeout ¶
WithTimeout marks the error as a timeout error in its context and returns the error. Example:
err := err.WithTimeout()
func (*Error) Wrap ¶
Wrap associates a cause error with this error, creating a chain. Returns the error unchanged if cause is nil. Example:
err := errors.New("failed").Wrap(errors.New("cause"))
func (*Error) WrapNotNil ¶
WrapNotNil wraps a cause error only if it is non-nil and returns the error. Example:
err := err.WrapNotNil(maybeError)
type ErrorCategory ¶
type ErrorCategory string
ErrorCategory is a string type for categorizing errors (e.g., "network", "validation").
type ErrorFormatter ¶
ErrorFormatter defines a function for custom error message formatting. Takes a slice of errors and returns a single formatted string.
type ErrorOpts ¶
type ErrorOpts struct {
SkipStack int // Number of stack frames to skip when capturing the stack trace.
}
ErrorOpts provides options for customizing error creation.
type ErrorPool ¶
type ErrorPool struct {
// contains filtered or unexported fields
}
ErrorPool is a high-performance, thread-safe pool for reusing *Error instances. Reduces allocation overhead by recycling errors; tracks hit/miss statistics.
func NewErrorPool ¶
func NewErrorPool() *ErrorPool
NewErrorPool creates a new ErrorPool instance. Initializes the pool with a New function that returns a fresh *Error with default smallContext.
func (*ErrorPool) Get ¶
Get retrieves an *Error from the pool or creates a new one if pooling is disabled or pool is empty. Resets are handled by Put; thread-safe; updates hit/miss stats when pooling is enabled.
type ExponentialBackoff ¶
type ExponentialBackoff struct{}
ExponentialBackoff provides an exponentially increasing delay for retry attempts.
type Group ¶ added in v1.3.0
type Group struct {
// contains filtered or unexported fields
}
Group runs goroutines concurrently and collects every error they return. The zero value is ready to use; options may be applied via NewGroup.
Example — fan-out with full error collection:
g := errors.NewGroup()
g.Go(func() error { return validateUser(id) })
g.Go(func() error { return validatePerms(id) })
if err := g.Wait(); err != nil {
// err is *MultiError containing all failures
log.Println(err)
}
func NewGroup ¶ added in v1.3.0
func NewGroup(opts ...GroupOption) *Group
NewGroup creates a Group with the given options applied.
func (*Group) Errors ¶ added in v1.3.0
Errors returns a snapshot of errors collected so far. Safe to call concurrently with Go/GoCtx; may be incomplete before Wait returns.
func (*Group) Go ¶ added in v1.3.0
Go starts fn in a new goroutine. Errors returned by fn are collected; nil returns are ignored. Thread-safe: MultiError.Add handles its own locking. cancelOnFirst is read-only after construction so no lock is needed.
func (*Group) GoCtx ¶ added in v1.3.0
GoCtx starts fn in a new goroutine, passing the group's context. If the group was created with GroupWithContext, fn receives a context that is cancelled when cancelOnFirst triggers or the parent is done.
type GroupOption ¶ added in v1.3.0
type GroupOption func(*Group)
GroupOption configures a Group.
func GroupWithContext ¶ added in v1.3.0
func GroupWithContext(ctx context.Context, cancelOnFirst bool) GroupOption
GroupWithContext attaches ctx to the Group. The ctx is passed to context-aware Go calls (GoCtx). If cancelOnFirst is true, the context is cancelled as soon as the first error is returned by any goroutine — useful for "cancel siblings on first failure" patterns.
func GroupWithLimit ¶ added in v1.3.0
func GroupWithLimit(n int) GroupOption
GroupWithLimit sets a maximum error limit on the underlying MultiError. Errors beyond the limit are dropped.
type HTTPOption ¶ added in v1.3.0
type HTTPOption func(*httpConfig)
HTTPOption configures an HTTPError call.
func WithBody ¶ added in v1.3.0
func WithBody(include bool) HTTPOption
WithBody controls whether the error message is written as the response body. Default is true.
func WithBodyFunc ¶ added in v1.3.0
func WithBodyFunc(fn func(error) string) HTTPOption
WithBodyFunc sets a custom function that produces the response body string from the error. Overrides WithBody when set.
Example — return JSON instead of plain text:
errors.HTTPError(w, err,
errors.WithBodyFunc(func(e error) string {
return fmt.Sprintf(`{"error":%q}`, e.Error())
}),
)
func WithFallbackCode ¶ added in v1.3.0
func WithFallbackCode(code int) HTTPOption
WithFallbackCode sets the HTTP status used when err carries no valid code. Default is 500 (Internal Server Error).
type InspectOption ¶ added in v1.3.0
type InspectOption func(*inspectConfig)
InspectOption configures an Inspect call.
func WithMaxDepth ¶ added in v1.3.0
func WithMaxDepth(n int) InspectOption
WithMaxDepth sets the maximum chain depth traversed before output is truncated. Default is 10.
func WithStackFrames ¶ added in v1.3.0
func WithStackFrames(n int) InspectOption
WithStackFrames sets the maximum number of stack frames printed per error node. Default is 3.
type LinearBackoff ¶
type LinearBackoff struct{}
LinearBackoff provides a linearly increasing delay for retry attempts.
type MultiError ¶
type MultiError struct {
// contains filtered or unexported fields
}
MultiError represents a thread-safe collection of errors with enhanced features. Supports limits, sampling, and custom formatting for error aggregation.
func NewMultiError ¶
func NewMultiError(opts ...MultiErrorOption) *MultiError
NewMultiError creates a new MultiError instance with optional configuration. Initial capacity is set to 4; applies options in the order provided.
func (*MultiError) Add ¶
func (m *MultiError) Add(errs ...error)
Add appends an error to the collection with optional sampling, limit checks, and duplicate prevention. Ignores nil errors and duplicates based on string equality; thread-safe.
func (*MultiError) Addf ¶
func (m *MultiError) Addf(format string, args ...interface{})
Addf formats and adds a new error to the collection.
func (*MultiError) Clear ¶
func (m *MultiError) Clear()
Clear removes all errors from the collection. Thread-safe; resets the slice while preserving capacity.
func (*MultiError) Count ¶
func (m *MultiError) Count() int
Count returns the number of errors in the collection. Thread-safe.
func (*MultiError) Error ¶
func (m *MultiError) Error() string
Error returns a formatted string representation of the errors. Returns empty string if no errors, single error message if one exists, or a formatted list using custom formatter or default if multiple; thread-safe.
func (*MultiError) Errors ¶
func (m *MultiError) Errors() []error
Errors returns a copy of the contained errors. Thread-safe; returns nil if no errors exist.
func (*MultiError) Filter ¶
func (m *MultiError) Filter(fn func(error) bool) *MultiError
Filter returns a new MultiError containing only errors that match the predicate. Thread-safe; preserves original configuration including limit, formatter, and sampling.
func (*MultiError) First ¶
func (m *MultiError) First() error
First returns the first error in the collection, if any. Thread-safe; returns nil if the collection is empty.
func (*MultiError) Has ¶
func (m *MultiError) Has() bool
Has reports whether the collection contains any errors. Thread-safe.
func (*MultiError) IsNull ¶
func (m *MultiError) IsNull() bool
IsNull checks if the MultiError is empty or contains only null errors. Returns true if empty or all errors are null (via IsNull() or empty message); thread-safe.
func (*MultiError) Last ¶
func (m *MultiError) Last() error
Last returns the most recently added error in the collection, if any. Thread-safe; returns nil if the collection is empty.
func (*MultiError) MarshalJSON ¶
func (m *MultiError) MarshalJSON() ([]byte, error)
MarshalJSON serializes the MultiError to JSON, including all contained errors and configuration metadata. Thread-safe; errors are serialized using their MarshalJSON method if available, otherwise as strings.
func (*MultiError) Merge ¶
func (m *MultiError) Merge(other *MultiError)
Merge combines another MultiError's errors into this one. Thread-safe; respects this instance’s limit and sampling settings; no-op if other is nil or empty.
func (*MultiError) Single ¶
func (m *MultiError) Single() error
Single returns nil if the collection is empty, the single error if only one exists, or the MultiError itself if multiple errors are present. Thread-safe; useful for unwrapping to a single error when possible.
func (*MultiError) String ¶
func (m *MultiError) String() string
String implements the Stringer interface for a concise string representation. Thread-safe; delegates to Error() for formatting.
func (*MultiError) Unwrap ¶
func (m *MultiError) Unwrap() []error
Unwrap returns a copy of the contained errors for multi-error unwrapping. Implements the errors.Unwrap interface; thread-safe; returns nil if empty.
type MultiErrorOption ¶
type MultiErrorOption func(*MultiError)
MultiErrorOption configures MultiError behavior during creation.
func WithFormatter ¶
func WithFormatter(f ErrorFormatter) MultiErrorOption
WithFormatter sets a custom error formatting function. Returns a MultiErrorOption for use with NewMultiError; overrides default formatting.
func WithLimit ¶
func WithLimit(n int) MultiErrorOption
WithLimit sets the maximum number of errors to store. Returns a MultiErrorOption for use with NewMultiError; 0 means unlimited, negative values are ignored.
func WithRand ¶
func WithRand(r *rand.Rand) MultiErrorOption
WithRand sets a custom random source for sampling, useful for testing. Returns a MultiErrorOption for use with NewMultiError; defaults to fastRand if nil.
func WithSampling ¶
func WithSampling(rate uint32) MultiErrorOption
WithSampling enables error sampling with a specified rate (1-100). Returns a MultiErrorOption for use with NewMultiError; caps rate at 100 for validity.
type Retry ¶
type Retry struct {
// contains filtered or unexported fields
}
Retry represents a retryable operation with configurable backoff and retry logic. Supports multiple attempts, delay strategies, jitter, and context-aware cancellation.
func NewRetry ¶
func NewRetry(options ...RetryOption) *Retry
NewRetry creates a new Retry instance with the given options. Defaults: 3 attempts, 100ms base delay, 10s max delay, exponential backoff with jitter, and retrying on IsRetryable errors; ensures retryIf is never nil.
func (*Retry) Attempts ¶
Attempts returns the configured maximum number of retry attempts. Includes the initial attempt in the count.
func (*Retry) Execute ¶
Execute runs the provided function with the configured retry logic. Returns nil on success or the last error if all attempts fail; respects context cancellation.
func (*Retry) ExecuteContext ¶
ExecuteContext runs the provided function with retry logic, respecting context cancellation. Returns nil on success or the last error if all attempts fail or context is cancelled.
func (*Retry) Transform ¶
func (r *Retry) Transform(opts ...RetryOption) *Retry
Transform creates a new Retry instance with modified configuration. Copies all settings from the original Retry and applies the given options.
type RetryOption ¶
type RetryOption func(*Retry)
RetryOption configures a Retry instance. Defines a function type for setting retry parameters.
func WithBackoff ¶
func WithBackoff(strategy BackoffStrategy) RetryOption
WithBackoff sets the backoff strategy using the BackoffStrategy interface. Returns a RetryOption; no-op if strategy is nil, retaining the existing strategy.
func WithContext ¶
func WithContext(ctx context.Context) RetryOption
WithContext sets the context for cancellation and deadlines. Returns a RetryOption; retains context.Background if ctx is nil.
func WithDelay ¶
func WithDelay(delay time.Duration) RetryOption
WithDelay sets the initial delay between retries. Returns a RetryOption; ensures non-negative delay by setting negatives to 0.
func WithJitter ¶
func WithJitter(jitter bool) RetryOption
WithJitter enables or disables jitter in the backoff delay. Returns a RetryOption; toggles random delay variation.
func WithMaxAttempts ¶
func WithMaxAttempts(maxAttempts int) RetryOption
WithMaxAttempts sets the maximum number of retry attempts. Returns a RetryOption; ensures at least 1 attempt by adjusting lower values.
func WithMaxDelay ¶
func WithMaxDelay(maxDelay time.Duration) RetryOption
WithMaxDelay sets the maximum delay between retries. Returns a RetryOption; ensures non-negative delay by setting negatives to 0.
func WithOnRetry ¶
func WithOnRetry(onRetry func(attempt int, err error)) RetryOption
WithOnRetry sets a callback to execute after each failed attempt. Returns a RetryOption; callback receives attempt number and error.
func WithRetryIf ¶
func WithRetryIf(retryIf func(error) bool) RetryOption
WithRetryIf sets the condition under which to retry. Returns a RetryOption; retains IsRetryable default if retryIf is nil.
type Sentinel ¶ added in v1.3.0
type Sentinel struct {
// contains filtered or unexported fields
}
Sentinel is a comparable, immutable error value safe to store as a package-level variable and match with errors.Is or a type switch.
Unlike Named(), which returns a new *Error instance on every call (making pointer equality unreliable), each call to Const() returns a unique stable pointer. Two sentinels with identical name/msg are still distinct values unless they are the same pointer — intentional, to avoid accidental aliasing.
func Const ¶ added in v1.3.0
Const creates a new sentinel error with the given name and message. Store the result as a package-level var; never call Const in a hot path.
Example:
var (
ErrNotFound = errors.Const("not_found", "resource not found")
ErrForbidden = errors.Const("forbidden", "access denied")
ErrBadRequest = errors.Const("bad_request", "invalid input")
)
func handle(err error) {
switch {
case errors.Is(err, ErrNotFound): // 404
case errors.Is(err, ErrForbidden): // 403
}
}
func (*Sentinel) As ¶ added in v1.3.0
As attempts to assign the sentinel to target if target is **Sentinel. Returns true if the assignment was made.
func (*Sentinel) Is ¶ added in v1.3.0
Is reports whether target is the same sentinel (pointer equality). This satisfies the errors.Is contract.
func (*Sentinel) LogValue ¶ added in v1.3.0
LogValue implements slog.LogValuer so a Sentinel can be passed directly to any slog logging call and rendered as a structured group.
Example:
slog.Error("lookup failed", "err", ErrNotFound)
// => err.error="resource not found", err.code="not_found"
func (*Sentinel) MarshalJSON ¶ added in v1.3.0
MarshalJSON serialises the sentinel to {"error":"...","code":"..."}.
func (*Sentinel) Name ¶ added in v1.3.0
Name returns the sentinel's name, useful for logging and diagnostics.
func (*Sentinel) Unwrap ¶ added in v1.3.0
Unwrap returns nil — sentinels are root errors with no cause chain. Satisfies the errors.Unwrap contract.
func (*Sentinel) With ¶ added in v1.3.0
With returns a new *Error that wraps this sentinel as its cause and carries the additional message msg. Use this to add call-site context to a sentinel without losing the ability to match the original with errors.Is.
Example:
var ErrNotFound = errors.Const("not_found", "resource not found")
// At call site:
err := ErrNotFound.With("user 42 not found")
errors.Is(err, ErrNotFound) // true — sentinel is in the cause chain
type Stream ¶ added in v1.3.0
type Stream[T any] struct { // contains filtered or unexported fields }
Stream processes a slice of items concurrently, collecting errors as they occur without stopping execution. Use Wait() to block until all items are done, or Each() to process errors as they arrive.
Example — collect all:
s := errors.NewStream(ctx, items, process, 8)
if err := s.Wait(); err != nil {
log.Println(err)
}
Example — process as they arrive:
s := errors.NewStream(ctx, items, process, 8)
s.Each(func(err error) { log.Println(err) })
func NewStream ¶ added in v1.3.0
NewStream creates a Stream that applies fn to every item in items using up to workers concurrent goroutines.
workers <= 0 defaults to len(items), running all items at once. Respects ctx: in-flight work completes but no new items start once ctx is done.
Example:
s := errors.NewStream(ctx, urls, func(url string) error {
return fetch(url)
}, 8)
func (*Stream[T]) Each ¶ added in v1.3.0
Each calls fn for every error produced by the stream, in the order they arrive. Blocks until all items have been processed.
Panics if called after Wait (or a second call to Each).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package main demonstrates basic usage of the errors package from github.com/olekukonko/errors.
|
Package main demonstrates basic usage of the errors package from github.com/olekukonko/errors. |
|
Package errmgr provides common error definitions and categories for use across applications.
|
Package errmgr provides common error definitions and categories for use across applications. |