Documentation
¶
Index ¶
- Variables
- func ContextWithOptions(ctx context.Context, opts ...Option) context.Context
- func DefineField[T any](name string) (FieldConstructor[T], FieldExtractor[T])
- type DebugStacker
- type Definition
- type Details
- type Error
- type Factory
- type FieldConstructor
- func (f FieldConstructor[T]) Key() FieldKey
- func (f FieldConstructor[T]) WithContextFunc(fn func(ctx context.Context) T) FieldConstructor[context.Context]
- func (f FieldConstructor[T]) WithErrorFunc(fn func(err error) T) FieldConstructor[error]
- func (f FieldConstructor[T]) WithHTTPRequestFunc(fn func(r *http.Request) T) FieldConstructor[*http.Request]
- func (f FieldConstructor[T]) WithValue(value T) FieldConstructorNoArgs[T]
- func (f FieldConstructor[T]) WithValueFunc(fn func() T) FieldConstructorNoArgs[T]
- type FieldConstructorNoArgs
- type FieldExtractor
- func (f FieldExtractor[T]) OrDefault(err error, value T) T
- func (f FieldExtractor[T]) OrFallback(err error, fn func(err error) T) T
- func (f FieldExtractor[T]) OrZero(err error) T
- func (f FieldExtractor[T]) WithDefault(value T) FieldExtractorSingleReturn[T]
- func (f FieldExtractor[T]) WithFallback(fn func(err error) T) FieldExtractorSingleReturn[T]
- func (f FieldExtractor[T]) WithZero() FieldExtractorSingleReturn[T]
- type FieldExtractorSingleReturn
- type FieldKey
- type FieldValue
- type Fields
- type Frame
- type Kind
- type Node
- type Nodes
- type Option
- func Formatter(f func(err Error, s fmt.State, verb rune)) Option
- func JSONMarshaler(f func(err Error) ([]byte, error)) Option
- func LogValuer(f func(err Error) slog.Value) Option
- func NoTrace() Option
- func StackDepth(depth int) Option
- func StackSkip(skip int) Option
- func StackSource(around, depth int) Option
- type PanicError
- type Presenter
- type Redacted
- func (r Redacted[T]) Format(s fmt.State, verb rune)
- func (r Redacted[T]) GoString() string
- func (r Redacted[T]) IsRedacted() bool
- func (r Redacted[T]) LogValue() slog.Value
- func (r Redacted[T]) MarshalBinary() ([]byte, error)
- func (r Redacted[T]) MarshalJSON() ([]byte, error)
- func (r Redacted[T]) MarshalText() ([]byte, error)
- func (r Redacted[T]) String() string
- func (r Redacted[T]) Value() T
- type Stack
- type StackTracer
Constants ¶
This section is empty.
Variables ¶
var (
// HTTPStatus attaches an HTTP status code.
HTTPStatus, HTTPStatusFrom = DefineField[int]("http_status")
// LogLevel attaches a log level of type `slog.Level`.
LogLevel, LogLevelFrom = DefineField[slog.Level]("log_level")
// TraceID attaches a trace or request ID.
TraceID, TraceIDFrom = DefineField[string]("trace_id")
// Domain labels the error with a service or subsystem name.
Domain, DomainFrom = DefineField[string]("domain")
// Provides a safe, user-facing hint message.
UserHint, UserHintFrom = DefineField[string]("user_hint")
// Public marks the error as safe to expose externally.
Public, IsPublic = public.WithValue(true), publicFrom.WithZero()
// Retryable marks the operation as retryable.
Retryable, IsRetryable = retryable.WithValue(true), retryableFrom.WithZero()
// RetryAfter recommends a delay to wait before retrying.
RetryAfter, RetryAfterFrom = DefineField[time.Duration]("retry_after")
// Unreportable prevents the error from being sent to error tracking.
Unreportable, IsUnreportable = unreportable.WithValue(true), unreportableFrom.WithZero()
// ExitCode sets the exit code for a CLI application.
ExitCode, ExitCodeFrom = DefineField[int]("exit_code")
// HelpURL provides a URL for documentation or help guides.
HelpURL, HelpURLFrom = DefineField[string]("help_url")
// DetailsFrom extracts diagnostic details from an error.
DetailsFrom FieldExtractor[Details] = detailsFrom
)
Functions ¶
func ContextWithOptions ¶
ContextWithOptions adds error options to a context. These options will be automatically applied when creating errors using Definition.With method.
func DefineField ¶
func DefineField[T any](name string) (FieldConstructor[T], FieldExtractor[T])
DefineField creates a field option constructor and extractor for the given field name. The constructor can be used to set a field value in error options, and the extractor can be used to retrieve the field value from errors.
NOTE: The identity of a field is determined by the returned constructor and extractor instances, not by the provided name string. This ensures that fields created by different calls to DefineField, even with the same name, are distinct and do not collide.
The name string is used as the key when an error's fields are serialized (e.g., to JSON). To avoid ambiguity in logs and other serialized representations, it is strongly recommended to use a unique name for each defined field.
Types ¶
type DebugStacker ¶
type DebugStacker interface {
DebugStack() string
}
DebugStacker returns a string that resembles the output of debug.Stack(). This is useful for integrating with Google Cloud Error Reporting. See: https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.events/report#ReportedErrorEvent
NOTE: The goroutine ID and state may differ from the actual one.
type Definition ¶
type Definition interface {
error
Factory
// Kind returns the kind of this error definition.
Kind() Kind
// Is reports whether this definition matches the given error.
Is(error) bool
// Fields returns the fields associated with this definition.
Fields() Fields
// With creates a new Factory and applies options from context first (if any),
// then the given opts. Later options override earlier ones.
With(context.Context, ...Option) Factory
// WithOptions creates a new Factory with the given options applied.
// Later options override earlier ones.
WithOptions(...Option) Factory
}
Definition represents an error definition with customizable options. It serves as a reusable template for creating structured errors with a specific kind, fields, and behavior (e.g., stack traces, formatting, serialization).
Definition can be used as a sentinel error for identity checks with errors.Is, similar to standard errors like io.EOF. It can also be configured with additional options using With or WithOptions to create a Factory for generating errors with context-specific or request-scoped data.
func Define ¶
func Define(kind Kind, opts ...Option) Definition
Define creates a new error definition with the specified kind and options.
NOTE: The error identity check performed by errors.Is relies on an internal identifier associated with each Definition instance, not on the string value of Kind.
While this means that using the same Kind string for different definitions will not cause incorrect identity checks, it is strongly recommended to use a unique Kind value across your application to prevent confusion in logs and monitoring tools.
type Details ¶ added in v0.2.1
Details represents a map of diagnostic details that can be attached to an error.
type Error ¶
type Error interface {
error
// Kind returns the type of this error.
Kind() Kind
// Fields returns the structured fields associated with this error.
Fields() Fields
// Stack returns the stack trace where this error was created.
Stack() Stack
// Unwrap returns the errors that this error wraps.
Unwrap() []error
// UnwrapTree returns all causes as a tree structure.
// This method includes cycle detection: when a circular reference is detected,
// the node that would create the cycle is excluded, ensuring the result remains acyclic.
// While circular references are rare in practice, this check serves as a defensive
// programming measure.
UnwrapTree() Nodes
}
Error extends the built-in error interface with additional functionality for structured error handling including kinds, fields, and stack traces.
Error instances are created from a Definition and remain immutable after creation. They provide rich context through Kind (error classification), Fields (structured data), and Stack (call stack information), while maintaining compatibility with standard Go error handling via errors.Is and errors.As.
Error chains are supported through Unwrap() for standard error unwrapping, and UnwrapTree() for accessing the full error tree with cycle detection.
type Factory ¶ added in v0.6.0
type Factory interface {
// New creates a new error with the given message using this definition.
New(msg string) error
// Errorf creates a new error with a formatted message using this definition.
Errorf(format string, args ...any) error
// Wrap wraps an existing error using this definition.
// Returns nil if cause is nil.
Wrap(cause error) error
// Wrapf wraps an existing error with a formatted message using this definition.
// Returns nil if cause is nil.
Wrapf(cause error, format string, args ...any) error
// Join creates a new error by joining multiple errors using this definition.
// Returns nil if all causes are nil.
Join(causes ...error) error
// Recover executes the given function and recovers from any panic that occurs within it.
// If a panic occurs, it wraps the panic as an error using this definition and returns it.
// If no panic occurs, it returns the function's return value as is.
// The resulting error implements PanicError interface to preserve the original panic value.
Recover(fn func() error) error
}
Factory is an interface for creating errors from a configured Definition. It provides only error creation methods, preventing misuse such as identity comparison (errors.Is) or further configuration (With/WithOptions).
Factory instances are typically created by Definition.With or Definition.WithOptions methods, and are intended to be used immediately for error creation rather than stored as sentinel values.
type FieldConstructor ¶ added in v0.2.5
FieldConstructor creates an Option that sets a field value.
func (FieldConstructor[T]) Key ¶ added in v0.3.1
func (f FieldConstructor[T]) Key() FieldKey
Key returns the key associated with this constructor.
func (FieldConstructor[T]) WithContextFunc ¶ added in v0.2.5
func (f FieldConstructor[T]) WithContextFunc(fn func(ctx context.Context) T) FieldConstructor[context.Context]
WithContextFunc creates a field option constructor that sets a value using a function that takes a context.
func (FieldConstructor[T]) WithErrorFunc ¶ added in v0.2.5
func (f FieldConstructor[T]) WithErrorFunc(fn func(err error) T) FieldConstructor[error]
WithErrorFunc creates a field option constructor that sets a value using a function that takes an error.
func (FieldConstructor[T]) WithHTTPRequestFunc ¶ added in v0.2.5
func (f FieldConstructor[T]) WithHTTPRequestFunc(fn func(r *http.Request) T) FieldConstructor[*http.Request]
WithHTTPRequestFunc creates a field option constructor that sets a value using a function that takes an HTTP request.
func (FieldConstructor[T]) WithValue ¶ added in v0.2.5
func (f FieldConstructor[T]) WithValue(value T) FieldConstructorNoArgs[T]
WithValue creates a field option constructor that sets a specific value.
func (FieldConstructor[T]) WithValueFunc ¶ added in v0.2.5
func (f FieldConstructor[T]) WithValueFunc(fn func() T) FieldConstructorNoArgs[T]
WithValueFunc creates a field option constructor that sets a value using a function.
type FieldConstructorNoArgs ¶ added in v0.2.5
FieldConstructorNoArgs creates an Option with a default value when called with no arguments.
type FieldExtractor ¶ added in v0.2.5
FieldExtractor extracts a field value from an error.
func (FieldExtractor[T]) OrDefault ¶ added in v0.2.5
func (f FieldExtractor[T]) OrDefault(err error, value T) T
OrDefault extracts the field value from the error, returning a default value if not found.
func (FieldExtractor[T]) OrFallback ¶ added in v0.2.5
OrFallback extracts the field value from the error, calling a function to obtain a value if not found.
func (FieldExtractor[T]) OrZero ¶ added in v0.2.5
func (f FieldExtractor[T]) OrZero(err error) T
OrZero extracts the field value from the error, returning the zero value if not found.
func (FieldExtractor[T]) WithDefault ¶ added in v0.2.5
func (f FieldExtractor[T]) WithDefault(value T) FieldExtractorSingleReturn[T]
WithDefault creates a field extractor that returns a default value if the field is not found.
func (FieldExtractor[T]) WithFallback ¶ added in v0.2.5
func (f FieldExtractor[T]) WithFallback(fn func(err error) T) FieldExtractorSingleReturn[T]
WithFallback creates a field extractor that calls a function to obtain a value if the field is not found.
type FieldExtractorSingleReturn ¶ added in v0.2.5
FieldExtractorSingleReturn extracts a field value from an error, returning only the value.
type FieldKey ¶
type FieldKey interface {
fmt.Stringer
// From creates a new FieldValue with the same type from the given value.
NewValue(value any) (FieldValue, bool)
// ZeroValue returns a FieldValue representing the zero value for the key's type.
ZeroValue() FieldValue
}
FieldKey represents a key for structured error fields.
type FieldValue ¶ added in v0.2.0
type FieldValue interface {
// Value returns the underlying value.
Value() any
// Equal checks if the value is equal to another value.
Equal(other any) bool
}
FieldValue represents a value for structured error fields.
type Fields ¶
type Fields interface {
// Get retrieves the value associated with the given key.
Get(key FieldKey) (FieldValue, bool)
// FindKeys finds all keys that match the given name.
FindKeys(name string) []FieldKey
// All returns an iterator over all key-value pairs sorted by insertion order.
All() iter.Seq2[FieldKey, FieldValue]
// Len returns the number of fields.
Len() int
// IsZero checks if there are no fields.
IsZero() bool
}
Fields represents a collection of structured error fields.
func FieldsFrom ¶ added in v0.7.0
FieldsFrom extracts the Fields from an error. It returns the Fields and true if the error implements the Fields() method and the Fields are non-empty. Otherwise, it returns nil and false.
type Kind ¶
type Kind string
Kind is a human-readable string that represents the type of an error. It is primarily used for classification and identification in structured logs, metrics, and API responses.
type Node ¶ added in v0.5.5
type Node struct {
// Error is the error at this node.
Error error
// Causes are the nested causes of this error.
Causes Nodes
// IsCyclic indicates whether this node is part of a cycle in the tree.
IsCyclic bool
}
Node represents a node in the cause tree.
func (*Node) MarshalJSON ¶ added in v0.5.5
MarshalJSON implements json.Marshaler for Node.
type Nodes ¶ added in v0.5.5
type Nodes []*Node
Nodes is a slice of error nodes representing an error tree structure.
func UnwrapTreeFrom ¶ added in v0.7.0
UnwrapTreeFrom extracts the error cause tree from an error. It returns the Nodes and true if the error implements the UnwrapTree() method and the returned Nodes are non-empty. Otherwise, it returns nil and false.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option represents a configuration option that can be applied to error definitions.
func JSONMarshaler ¶
JSONMarshaler overrides the default `json.Marshaler` behavior.
func StackDepth ¶ added in v0.1.8
StackDepth sets the depth of the stack trace capture (default: 32).
func StackSource ¶ added in v0.8.0
StackSource enables source code display for stack traces. It shows around lines before and after each stack frame in %+v output. The depth parameter controls how many frames to show source for:
- depth > 0: show source for the first depth frames
- depth == -1: show source for all frames
- depth == 0: no source display (no-op)
type PanicError ¶ added in v0.1.4
type Presenter ¶ added in v0.6.0
type Presenter interface {
// FormatError formats the error using this definition's custom formatter if set,
// otherwise uses the default format implementation.
FormatError(err Error, s fmt.State, verb rune)
// MarshalErrorJSON marshals the error to JSON using this definition's custom marshaler if set,
// otherwise uses the default JSON structure.
MarshalErrorJSON(err Error) ([]byte, error)
// MakeErrorLogValue returns a slog.Value representing the error using this definition's custom log valuer if set,
// otherwise uses the default log structure.
MakeErrorLogValue(err Error) slog.Value
// BuildCauseTree returns all causes as a tree structure.
// This method includes cycle detection: when a circular reference is detected,
// the node that would create the cycle is excluded, ensuring the result remains acyclic.
// While circular references are rare in practice, this check serves as a defensive
// programming measure.
BuildCauseTree(err Error) Nodes
}
Presenter provides error presentation methods for formatting, serialization, and logging. These methods are primarily used internally by Error implementations and are not typically called directly by application code.
type Redacted ¶ added in v0.2.4
type Redacted[T any] struct { // contains filtered or unexported fields }
Redacted[T] wraps a value so it always renders as "[REDACTED]" when printed, marshaled, or logged (fmt, json, slog), while still allowing access to the original value via Value(). Use this to prevent accidental exposure of sensitive data in logs/output.
func Redact ¶ added in v0.2.4
Redact wraps value in a Redacted[T], which always renders as "[REDACTED]" when printed, marshaled, or logged (fmt, json, slog), while still allowing access to the original value via Value(). Use this to prevent accidental exposure of sensitive data in logs/output.
func (Redacted[T]) Format ¶ added in v0.2.4
Format implements fmt.Formatter, always rendering as "[REDACTED]" regardless of the format verb.
func (Redacted[T]) GoString ¶ added in v0.4.0
GoString implements fmt.GoStringer, always returning "[REDACTED]" for %#v format.
func (Redacted[T]) IsRedacted ¶ added in v0.7.1
IsRedacted returns true. This method allows identifying Redacted[T] values via interface without knowing the type parameter T.
func (Redacted[T]) LogValue ¶ added in v0.2.4
LogValue implements slog.LogValuer, always logging as "[REDACTED]".
func (Redacted[T]) MarshalBinary ¶ added in v0.4.0
MarshalBinary implements encoding.BinaryMarshaler, always returning "[REDACTED]" as bytes.
func (Redacted[T]) MarshalJSON ¶ added in v0.2.4
MarshalJSON implements json.Marshaler, always marshaling as "[REDACTED]".
func (Redacted[T]) MarshalText ¶ added in v0.2.4
MarshalText implements encoding.TextMarshaler, always returning "[REDACTED]" as text.
type Stack ¶
type Stack interface {
// Frames returns the stack trace as structured frame information.
Frames() []Frame
// HeadFrame returns the top frame of the stack trace.
HeadFrame() (Frame, bool)
// FramesAndSource returns an iterator that yields frames and their source code snippets.
// Source code will be empty string if not available or if the frame exceeds the configured depth.
FramesAndSource() iter.Seq2[Frame, string]
// Len returns the number of frames in the stack trace.
Len() int
// IsZero returns true if the stack trace is empty.
IsZero() bool
}
Stack represents a stack trace captured when an error was created.
type StackTracer ¶ added in v0.7.2
type StackTracer interface {
StackTrace() []uintptr
}
StackTracer provides access to the low-level stack trace representation as program counters. This interface is intended for specialized use cases such as error reporting tools, tracing systems, or custom stack trace processing.