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.
pool.go
Package errors provides utilities for error handling, including a flexible retry mechanism.
Package errors provides utility functions for error handling, including stack trace capture and function name extraction.
Index ¶
- Constants
- func As(err error, target interface{}) bool
- func Caller(skip int) (file string, line int, function string)
- func Category(err error) string
- func Code(err error) int
- func Configure(cfg Config)
- func Context(err error) map[string]interface{}
- func Count(err error) uint64
- func ExecuteReply[T any](r *Retry, fn func() (T, error)) (T, error)
- func Find(err error, pred func(error) bool) error
- func FmtErrorCheck(format string, args ...interface{}) (result string, err error)
- func FormatError(err error) string
- func Has(err error) bool
- func HasContextKey(err error, key string) bool
- func Inspect(err error)
- func InspectError(err *Error)
- 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 Name(err error) string
- 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) 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 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(format string, 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) 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 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
Constants ¶
const (
DefaultCode = 500 // Default HTTP status code for errors if not specified.
)
Constants defining default configuration and context keys.
Variables ¶
This section is empty.
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 Caller ¶
Caller returns the file, line, and function name of the caller at the specified skip level. Skip=0 returns the caller of this function, 1 returns its caller, etc.; returns "unknown" if no caller found.
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 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 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 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 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 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. Includes message, name, context, stack trace, and cause for *Error types; just message for others; "<nil>" if nil.
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)
Inspect provides detailed examination of an error, handling both single errors and MultiError
func InspectError ¶
func InspectError(err *Error)
InspectError provides detailed inspection of a specific *Error instance
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 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 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) Tag ¶
func (c *Chain) Tag(category ErrorCategory) *Chain
Tag sets an error category for the last step.
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 frees errors to pool after use.
}
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 Errorf ¶
Errorf is an alias for Newf, providing a familiar interface compatible with fmt.Errorf. It creates a formatted error without capturing a stack trace. See Newf for full details on formatting, including %w support for error wrapping.
Example:
err := errors.Errorf("failed: %w", errors.New("cause"))
// err.Error() == "failed: 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 prevent memory leaks when autoFree is false. 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) 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 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.
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. |