Documentation
¶
Overview ¶
@index Context helpers for propagating trace IDs, fields, and cancellation causes into trace errors.
@index Typed error categories and retryability rules for trace errors.
@index Generic Result and Pipeline helpers for composing trace-aware success and failure flows.
@index slog integration for serializing trace errors and automatically expanding error attributes in log records.
@index Translation of operating system, filesystem, and network errors into typed trace categories.
@index Errno-based classification of network and resource-exhaustion failures on unix and windows.
Package trace provides enhanced error handling with stack traces, structured logging support, and full compatibility with Go 1.20+ error handling. @index Core error wrapping, stack capture, and structured error inspection APIs.
Index ¶
- func AccessDenied(msgAndArgs ...any) error
- func Aggregate(errs ...error) error
- func AlreadyExists(msgAndArgs ...any) error
- func As[T error](err error) (T, bool)
- func BadParameter(msgAndArgs ...any) error
- func Canceled(err error, msgAndArgs ...any) error
- func CheckContext(ctx context.Context) error
- func Conflict(msgAndArgs ...any) error
- func ConnectionProblem(err error, msgAndArgs ...any) error
- func ContextWithField(ctx context.Context, key string, value any) context.Context
- func ContextWithFields(ctx context.Context, fields map[string]any) context.Context
- func ContextWithTraceID(ctx context.Context, traceID string) context.Context
- func ConvertSystemError(err error) error
- func DebugReport(err error) string
- func DetachedContext(ctx context.Context) context.Context
- func DoValue[T any](c *Contextualizer, fn func() (T, error)) (T, error)
- func Errorf(format string, args ...any) error
- func Errors(err error) iter.Seq[error]
- func FieldsFromContext(ctx context.Context) map[string]any
- func FromContext(ctx context.Context) error
- func GetFields(err error) map[string]any
- func IsAccessDenied(err error) bool
- func IsAlreadyExists(err error) bool
- func IsBadParameter(err error) bool
- func IsCanceled(err error) bool
- func IsConflict(err error) bool
- func IsConnectionProblem(err error) bool
- func IsDeadlineExceeded(err error) bool
- func IsLimitExceeded(err error) bool
- func IsNotFound(err error) bool
- func IsNotImplemented(err error) bool
- func IsRetryable(err error) bool
- func IsTimeout(err error) bool
- func IsUnauthenticated(err error) bool
- func LimitExceeded(msgAndArgs ...any) error
- func LogDebug(ctx context.Context, logger *slog.Logger, msg string, err error, ...)
- func LogError(ctx context.Context, logger *slog.Logger, msg string, err error, ...)
- func LogWarn(ctx context.Context, logger *slog.Logger, msg string, err error, ...)
- func Must[T any](r Result[T]) T
- func MustValue[T any](value T, err error) T
- func New(msg string) error
- func NotFound(msgAndArgs ...any) error
- func NotImplemented(msgAndArgs ...any) error
- func SlogError(err error) slog.Attr
- func SlogErrorValue(err error) slog.Value
- func Timeout(err error, msgAndArgs ...any) error
- func TraceIDFromContext(ctx context.Context) string
- func Unauthenticated(msgAndArgs ...any) error
- func UserMessage(err error) string
- func WithCancelCause(parent context.Context) (context.Context, context.CancelCauseFunc)
- func WithField(err error, key string, value any) error
- func WithFields(err error, fields map[string]any) error
- func WithTimeoutCause(parent context.Context, d time.Duration, cause error) (context.Context, context.CancelFunc)
- func Wrap(err error, msg ...string) error
- func WrapAccessDenied(err error, msgAndArgs ...any) error
- func WrapAlreadyExists(err error, msgAndArgs ...any) error
- func WrapBadParameter(err error, msgAndArgs ...any) error
- func WrapContext(ctx context.Context, err error, msg ...string) error
- func WrapIfContextDone(ctx context.Context, err error) error
- func WrapLimitExceeded(err error, msgAndArgs ...any) error
- func WrapNotFound(err error, msgAndArgs ...any) error
- func WrapUnauthenticated(err error, msgAndArgs ...any) error
- func WrapWithFields(err error, fields map[string]any, msg ...string) error
- func Wrapf(err error, format string, args ...any) error
- type AccessDeniedError
- type AggregateError
- type AlreadyExistsError
- type BadParameterError
- type CanceledError
- type ConflictError
- type ConnectionProblemError
- type Contextualizer
- type ErrorAccessDenied
- type ErrorAlreadyExists
- type ErrorBadParameter
- type ErrorCanceled
- type ErrorConflict
- type ErrorConnectionProblem
- type ErrorHandler
- type ErrorLimitExceeded
- type ErrorNotFound
- type ErrorNotImplemented
- type ErrorRetryable
- type ErrorTimeout
- type ErrorUnauthenticated
- type Frame
- type Frames
- type LimitExceededError
- type NotFoundError
- type NotImplementedError
- type Pipeline
- func (p *Pipeline[T]) Recover(fn func(error) (T, error)) *Pipeline[T]
- func (p *Pipeline[T]) RecoverWith(defaultVal T) *Pipeline[T]
- func (p *Pipeline[T]) Result() (T, error)
- func (p *Pipeline[T]) Then(fn func(T) (T, error)) *Pipeline[T]
- func (p *Pipeline[T]) ThenDo(fn func(T) error) *Pipeline[T]
- func (p *Pipeline[T]) ToResult() Result[T]
- type Result
- func Collect[T any](results ...Result[T]) Result[[]T]
- func Err[T any](err error) Result[T]
- func ErrMsg[T any](msg string) Result[T]
- func FlatMap[T, U any](r Result[T], fn func(T) Result[U]) Result[U]
- func Map[T, U any](r Result[T], fn func(T) U) Result[U]
- func MapErr[T any](r Result[T], fn func(error) error) Result[T]
- func Ok[T any](value T) Result[T]
- func Try[T any](value T, err error) Result[T]
- type TimeoutError
- type TraceError
- type TraceErrorReplacer
- type UnauthenticatedError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AccessDenied ¶
@intent classify authorization failures so callers can deny access consistently. @domainRule access denied errors are classified as HTTP 403 by the tracehttp package. @ensures records the current call site as the first trace frame. AccessDenied creates a new AccessDeniedError
func Aggregate ¶
@intent preserve multiple concurrent failures as one error value for later inspection. @domainRule nil errors are discarded so only real failures participate in aggregation. @ensures returns nil for an all-nil input set and the sole error unchanged for a single failure. Aggregate combines multiple errors into a single error using errors.Join (Go 1.20+)
func AlreadyExists ¶
@intent classify duplicate-resource failures so callers can branch on uniqueness semantics. @domainRule already exists errors are classified as HTTP 409 by the tracehttp package. @ensures records the current call site as the first trace frame. AlreadyExists creates a new AlreadyExistsError
func As ¶
@intent perform typed error extraction without repeating target boilerplate at call sites. @ensures returns the zero value of T and false when no matching error is found. As is a generic version of errors.As
func BadParameter ¶
@intent classify invalid input so callers can branch on client-side request errors. @domainRule bad parameter errors are classified as HTTP 400 by the tracehttp package. @ensures records the current call site as the first trace frame. BadParameter creates a new BadParameterError
func Canceled ¶
@intent wrap an existing cancellation cause as a typed trace error. @domainRule returns nil unchanged when the source error is nil. @ensures records the current call site as the first trace frame. Canceled wraps err as a CanceledError.
func CheckContext ¶
@intent provide a cheap guard for aborting work when the context is already done. @ensures returns nil while the context is still usable and a traced context error otherwise. CheckContext checks if context is still valid and returns error if not
func Conflict ¶
@intent classify state mismatches that prevent the requested operation from succeeding. @domainRule conflict errors are classified as HTTP 409 by the tracehttp package. @ensures records the current call site as the first trace frame. Conflict creates a new ConflictError
func ConnectionProblem ¶
@intent mark infrastructure or network failures as transient connection problems. @domainRule connection problems are retryable and map to HTTP 503. @ensures prepends the current call site to any existing trace frames on the returned error. @ensures returns nil unchanged when the source error is nil. ConnectionProblem creates a new ConnectionProblemError. If err is nil, returns nil.
func ContextWithField ¶
@intent add one request-scoped field so later trace wrapping can include it. @domainRule the new value overrides an existing field with the same key. @mutates returns a derived context with an updated trace fields map. ContextWithField adds a single field to the context
func ContextWithFields ¶
@intent accumulate request-scoped metadata that should be copied into later trace errors. @domainRule new field values override existing keys from the parent context. @mutates returns a derived context with a merged trace fields map. ContextWithFields adds fields to the context for error enrichment
func ContextWithTraceID ¶
@intent attach a request-scoped trace identifier so downstream errors and logs can be correlated. @mutates returns a derived context carrying the trace_id value. ContextWithTraceID adds a trace ID to the context
func ConvertSystemError ¶
@intent give callers one entry point that turns stdlib failures into trace's typed categories. @domainRule the first matching category wins, checked from most specific to least. @domainRule an error that already carries a trace category is returned unchanged so existing classification is never downgraded. @domainRule the converted error carries no trace message, so the operating system string stays in the cause for debugging instead of becoming a client-facing HTTP message. @ensures returns nil for nil input and the original error when no category applies. ConvertSystemError converts an operating system, filesystem, or network error into the matching typed trace error.
The original error stays reachable through errors.Is and errors.As. Errors that no rule matches are returned unchanged rather than forced into a category, so the caller can still wrap them itself.
func DebugReport ¶
@intent render a full developer-facing report for nested and aggregated error chains. @domainRule aggregate errors must include every branch in the rendered report. @ensures returns an empty string when no error is provided. DebugReport returns a detailed report of the error chain
func DetachedContext ¶
@intent keep request metadata available for background work that must outlive request cancellation. @domainRule inherited values are preserved while cancellation is detached from the parent. DetachedContext returns a context that carries the parent's values but is not canceled when the parent is canceled (Go 1.21+). Useful for background cleanup or logging that should outlive the request.
func DoValue ¶
func DoValue[T any](c *Contextualizer, fn func() (T, error)) (T, error)
@intent run a value-returning function and preserve its result while enriching any error with trace metadata. @ensures returns the function's value unchanged alongside a wrapped error when the call fails. DoValue executes a function returning a value and wraps any error
func Errorf ¶
@intent create a traceable error from formatted application context. @ensures records the current call site as the first trace frame. @ensures allocates structured fields storage lazily on first field attachment. Errorf creates a new error with formatted message and stack trace
func Errors ¶
@intent iterate every error reachable from wrapped and aggregated trace errors. @domainRule aggregate branches are traversed recursively, not flattened into a single message. @ensures yields each reachable error once per traversal path until the consumer stops. Errors returns an iterator over the error chain (Go 1.23+). It yields each error in the chain by following Unwrap() error and recursively traversing Unwrap() []error (e.g., AggregateError).
func FieldsFromContext ¶
@intent expose request-scoped trace metadata without leaking mutable context state. @ensures returns a defensive copy of stored fields when trace metadata exists. FieldsFromContext retrieves fields from context. Returns a copy of the fields to prevent external mutation of the context value.
func FromContext ¶
@intent translate context cancellation and deadline signals into trace-aware error values. @domainRule context.Cause is preferred so the original cancellation reason is preserved. @ensures captures the current call site and copies trace metadata from the context into the returned error. @ensures returns nil when the context has not been canceled. FromContext checks for context errors and wraps them appropriately. Uses context.Cause (Go 1.20+) to capture the cancellation cause when available, preserving the original reason for cancellation rather than just context.Canceled.
func GetFields ¶
@intent expose structured trace metadata for logging, transport, or inspection layers. @ensures returns a defensive copy of the stored fields when trace data exists. GetFields extracts fields from an error if available. Returns a copy of the fields to prevent external mutation.
func IsAccessDenied ¶
@intent detect authorization failures anywhere in an error chain. @ensures returns false for nil errors. IsAccessDenied checks if error is an access denied error
func IsAlreadyExists ¶
@intent detect duplicate-resource failures anywhere in an error chain. @ensures returns false for nil errors. IsAlreadyExists checks if error is an already exists error
func IsBadParameter ¶
@intent detect caller-input failures anywhere in an error chain. @ensures returns false for nil errors. IsBadParameter checks if error is a bad parameter error
func IsCanceled ¶
@intent detect cancellation semantics anywhere in an error chain. @ensures returns false for nil errors. IsCanceled checks if an error is a cancellation error
func IsConflict ¶
@intent detect state-conflict failures anywhere in an error chain. @ensures returns false for nil errors. IsConflict checks if error is a conflict error
func IsConnectionProblem ¶
@intent detect transient transport or infrastructure failures anywhere in an error chain. @ensures returns false for nil errors. IsConnectionProblem checks if error is a connection problem
func IsDeadlineExceeded ¶
@intent detect deadline-expired failures across both context and trace timeout wrappers. @ensures returns false for nil errors. IsDeadlineExceeded checks if an error is due to deadline exceeded
func IsLimitExceeded ¶
@intent detect throttling or quota failures anywhere in an error chain. @ensures returns false for nil errors. IsLimitExceeded checks if error is a limit exceeded error
func IsNotFound ¶
@intent detect missing-resource failures anywhere in an error chain. @ensures returns false for nil errors. IsNotFound checks if error is a not found error
func IsNotImplemented ¶
@intent detect unsupported-operation failures anywhere in an error chain. @ensures returns false for nil errors. IsNotImplemented checks if error is a not implemented error
func IsRetryable ¶
@intent detect failures that explicitly advertise retry-safe semantics. @ensures returns false for nil errors. IsRetryable checks if error is retryable
func IsTimeout ¶
@intent detect timeout failures anywhere in an error chain. @ensures returns false for nil errors. IsTimeout checks if error is a timeout error
func IsUnauthenticated ¶
@intent detect authentication failures anywhere in an error chain. @ensures returns false for nil errors. IsUnauthenticated checks if error is an unauthenticated error.
func LimitExceeded ¶
@intent classify quota or rate-limit failures so callers can branch on throttling semantics. @domainRule limit exceeded errors are retryable and map to HTTP 429. @ensures records the current call site as the first trace frame. LimitExceeded creates a new LimitExceededError
func LogDebug ¶
@intent log an error at debug level using the trace serialization schema. @ensures does nothing when the input error is nil.
func LogError ¶
@intent log an error at error level using the trace serialization schema. @ensures does nothing when the input error is nil.
func LogWarn ¶
@intent log an error at warn level using the trace serialization schema. @ensures does nothing when the input error is nil.
func Must ¶
@intent provide concise success-only access in contexts where failure should panic. @domainRule panics when the Result contains an error. Must unwraps a Result, panicking on error
func MustValue ¶
@intent collapse a Go-style value-plus-error pair when failure should panic immediately. @domainRule panics with a wrapped trace error when err is non-nil. MustValue unwraps a (value, error) pair, panicking on error
func New ¶
@intent create a fresh traceable application error at the current call site. @ensures records the current call site as the first trace frame. @ensures allocates structured fields storage lazily on first field attachment. New creates a new error with stack trace
func NotFound ¶
@intent classify a missing resource so callers can branch on lookup failure semantics. @domainRule not found errors are classified as HTTP 404 by the tracehttp package. @ensures records the current call site as the first trace frame. NotFound creates a new NotFoundError
Example ¶
package main
import (
"fmt"
"github.com/tae2089/trace/v2"
)
func main() {
err := trace.NotFound(fmt.Sprintf("user %s not found", "alice"))
if trace.IsNotFound(err) {
fmt.Println("User not found!")
}
}
Output: User not found!
func NotImplemented ¶
@intent classify unsupported behavior so callers can surface capability gaps consistently. @domainRule not implemented errors are classified as HTTP 501 by the tracehttp package. @ensures records the current call site as the first trace frame. NotImplemented creates a new NotImplementedError
func SlogError ¶
@intent convert trace errors into a structured slog group that preserves message, cause, trace, and fields. @domainRule plain errors degrade to a minimal message-only structure instead of losing log compatibility. @ensures returns an empty slog.Attr when no error is provided. SlogError returns slog attributes for an error. Schema matches TraceError.LogValue: {"message":..., "cause":..., "trace":[...], "fields":{...}}
func SlogErrorValue ¶
@intent expose the trace-aware slog representation as a Value for callers building custom attributes. @ensures returns an empty string value when no error is provided. SlogErrorValue returns a slog.Value for an error
func Timeout ¶
@intent classify operations that exceeded their allowed completion window. @domainRule timeout errors are retryable and map to HTTP 504. @ensures prepends the current call site to any existing trace frames on the returned error. @ensures returns nil unchanged when the source error is nil. Timeout creates a new TimeoutError. If err is nil, returns nil.
func TraceIDFromContext ¶
@intent retrieve the request-scoped trace identifier for correlation in logs and errors. @ensures returns an empty string when the context has no trace ID. TraceIDFromContext retrieves the trace ID from context
func Unauthenticated ¶
@intent classify authentication failures separately from authorization failures. @domainRule unauthenticated errors map to HTTP 401 and expose only a fixed client message. @ensures records the current call site and keeps the supplied message for diagnostics only. Unauthenticated creates a new UnauthenticatedError.
func UserMessage ¶
@intent extract the safest high-level message to show outside debugging channels. @domainRule prefer explicit TraceError messages before falling back to wrapped causes. @ensures returns an empty string when no error is provided. UserMessage returns a user-friendly error message without stack traces
func WithCancelCause ¶
@intent expose cancel-cause semantics through the trace package API so callers can preserve shutdown reasons. @ensures returned contexts can later surface their cause via context.Cause. WithCancelCause returns a context with a CancelCauseFunc (Go 1.20+). The cause can later be retrieved via context.Cause(ctx).
func WithField ¶
@intent attach one diagnostic attribute without mutating the original error instance. @domainRule built-in trace wrapper types are preserved when replacing the inner TraceError. @mutates adds or replaces a single field on the returned error copy. @ensures returns nil unchanged when no source error is provided. WithField adds a field to the error for structured logging. It returns a new wrapper error with the field added, preserving the original error immutably.
func WithFields ¶
@intent attach multiple diagnostic attributes without mutating the original error instance. @domainRule later field values override earlier values for the same key. @mutates merges the provided fields into the returned error copy. @ensures returns nil unchanged when no source error is provided.
func WithTimeoutCause ¶
func WithTimeoutCause(parent context.Context, d time.Duration, cause error) (context.Context, context.CancelFunc)
@intent create a timeout that preserves an explicit business cause for later error wrapping. @ensures the returned context is canceled after the deadline with the supplied cause. WithTimeoutCause returns a context that is canceled after the given duration with the specified cause error (Go 1.21+).
func Wrap ¶
@intent preserve the original error while adding call-site debugging context. @domainRule typed errors stay discoverable through the Err chain for errors.Is and errors.As. @ensures prepends the current call site to any existing trace frames on the returned error. @ensures returns nil unchanged when no source error is provided. Wrap wraps an error with stack trace information. If err is nil, Wrap returns nil. Wrap always creates a new TraceError, preserving the original error (including typed errors like NotFoundError) in the Err field.
Example ¶
Example output
package main
import (
"errors"
"fmt"
"github.com/tae2089/trace/v2"
)
func main() {
err := errors.New("connection refused")
wrapped := trace.Wrap(err, "failed to connect to database")
fmt.Println(wrapped)
}
Output:
func WrapAccessDenied ¶
@intent preserve a lower-level cause while surfacing it as an authorization failure. @domainRule returns nil unchanged when the source error is nil. @ensures prepends the current call site to any existing trace frames on the returned error. WrapAccessDenied wraps an error as AccessDeniedError
func WrapAlreadyExists ¶
@intent preserve an existing cause while reclassifying it as a duplicate-resource failure. @domainRule returns nil unchanged when the source error is nil. @ensures prepends the current call site to any existing trace frames on the returned error. WrapAlreadyExists wraps an error as AlreadyExistsError
func WrapBadParameter ¶
@intent preserve an existing cause while surfacing it as a client input failure. @domainRule returns nil unchanged when the source error is nil. @ensures prepends the current call site to any existing trace frames on the returned error. WrapBadParameter wraps an error as BadParameterError
func WrapContext ¶
@intent combine ordinary failures with request trace metadata before they cross a boundary. @domainRule trace_id and stored context fields are copied into the returned error when present. @ensures returns nil unchanged when no source error is provided. WrapContext wraps an error with context information
func WrapIfContextDone ¶
@intent preserve both the operation failure and any concurrent context cancellation signal. @domainRule when the context is done, the returned error aggregates the original error with the context-derived failure. @ensures returns nil unchanged when no source error is provided. WrapIfContextDone wraps the error with context info if context is done
func WrapLimitExceeded ¶
@intent reclassify an existing failure as a quota or rate-limit failure while keeping its cause. @domainRule returns nil unchanged when the source error is nil. @ensures prepends the current call site to any existing trace frames on the returned error. WrapLimitExceeded wraps an existing error as a LimitExceededError.
func WrapNotFound ¶
@intent preserve an existing cause while reclassifying it as a missing-resource failure. @domainRule returns nil unchanged when the source error is nil. @ensures prepends the current call site to any existing trace frames on the returned error. WrapNotFound wraps an error as NotFoundError
func WrapUnauthenticated ¶
@intent preserve a lower-level cause while classifying an authentication failure. @domainRule returns nil unchanged when the source error is nil. WrapUnauthenticated wraps an error as UnauthenticatedError.
func WrapWithFields ¶
@intent enrich an error with structured diagnostics that can flow into logs and HTTP responses. @domainRule field attachment must not discard the wrapped error chain. @mutates adds key-value metadata to the returned TraceError fields map. @ensures returns nil unchanged when no source error is provided. WrapWithFields wraps an error with stack trace and structured fields
func Wrapf ¶
@intent preserve the original error while adding formatted debugging context. @domainRule typed errors stay discoverable through the Err chain for errors.Is and errors.As. @ensures returns nil unchanged when no source error is provided. Wrapf wraps an error with stack trace and a formatted message.
Types ¶
type AccessDeniedError ¶
type AccessDeniedError struct {
*TraceError
}
@intent mark authorization failures so callers can deny access consistently. AccessDeniedError represents an access denied error
func (*AccessDeniedError) Error ¶
func (e *AccessDeniedError) Error() string
@intent delegate user-facing string rendering to the embedded TraceError.
func (*AccessDeniedError) IsAccessDenied ¶
func (e *AccessDeniedError) IsAccessDenied() bool
@intent advertise authorization-failure semantics for behavior-based error checks.
func (*AccessDeniedError) Unwrap ¶
func (e *AccessDeniedError) Unwrap() error
@intent expose the embedded TraceError to standard Go error traversal.
type AggregateError ¶
type AggregateError struct {
Errs []error
}
@intent preserve multiple related failures as one traversable error tree. AggregateError holds multiple errors
func (*AggregateError) Error ¶
func (e *AggregateError) Error() string
@intent render a readable summary that includes every child error in the aggregate. @ensures includes the number of collected errors in the output.
func (*AggregateError) Unwrap ¶
func (e *AggregateError) Unwrap() []error
@intent expose all child errors so callers can traverse the aggregate tree. Unwrap returns the list of errors (Go 1.20+ multiple error unwrapping)
type AlreadyExistsError ¶
type AlreadyExistsError struct {
*TraceError
}
@intent mark failures caused by uniqueness or duplicate-resource conflicts. AlreadyExistsError represents an "already exists" error
func (*AlreadyExistsError) Error ¶
func (e *AlreadyExistsError) Error() string
@intent delegate user-facing string rendering to the embedded TraceError.
func (*AlreadyExistsError) IsAlreadyExists ¶
func (e *AlreadyExistsError) IsAlreadyExists() bool
@intent advertise duplicate-resource semantics for behavior-based error checks.
func (*AlreadyExistsError) Unwrap ¶
func (e *AlreadyExistsError) Unwrap() error
@intent expose the embedded TraceError to standard Go error traversal.
type BadParameterError ¶
type BadParameterError struct {
*TraceError
}
@intent mark failures caused by invalid caller input or malformed parameters. BadParameterError represents an invalid parameter error
func (*BadParameterError) Error ¶
func (e *BadParameterError) Error() string
@intent delegate user-facing string rendering to the embedded TraceError.
func (*BadParameterError) IsBadParameter ¶
func (e *BadParameterError) IsBadParameter() bool
@intent advertise invalid-input semantics for behavior-based error checks.
func (*BadParameterError) Unwrap ¶
func (e *BadParameterError) Unwrap() error
@intent expose the embedded TraceError to standard Go error traversal.
type CanceledError ¶
type CanceledError struct {
*TraceError
}
@intent represent context cancellation as a typed trace error that still carries the original cause. CanceledError represents a context cancellation error
func (*CanceledError) Error ¶
func (e *CanceledError) Error() string
@intent delegate user-facing string rendering to the embedded TraceError.
func (*CanceledError) IsCanceled ¶
func (e *CanceledError) IsCanceled() bool
@intent advertise cancellation semantics for behavior-based error checks.
func (*CanceledError) Unwrap ¶
func (e *CanceledError) Unwrap() error
@intent expose the embedded TraceError to standard Go error traversal.
type ConflictError ¶
type ConflictError struct {
*TraceError
}
@intent mark state conflicts that block the requested operation until data changes. ConflictError represents a conflict error
func (*ConflictError) Error ¶
func (e *ConflictError) Error() string
@intent delegate user-facing string rendering to the embedded TraceError.
func (*ConflictError) IsConflict ¶
func (e *ConflictError) IsConflict() bool
@intent advertise state-conflict semantics for behavior-based error checks.
func (*ConflictError) Unwrap ¶
func (e *ConflictError) Unwrap() error
@intent expose the embedded TraceError to standard Go error traversal.
type ConnectionProblemError ¶
type ConnectionProblemError struct {
*TraceError
}
@intent mark infrastructure or transport failures that may succeed on retry. ConnectionProblemError represents a connection error
func (*ConnectionProblemError) Error ¶
func (e *ConnectionProblemError) Error() string
@intent delegate user-facing string rendering to the embedded TraceError.
func (*ConnectionProblemError) IsConnectionProblem ¶
func (e *ConnectionProblemError) IsConnectionProblem() bool
@intent advertise transport-failure semantics for behavior-based error checks.
func (*ConnectionProblemError) IsRetryable ¶
func (e *ConnectionProblemError) IsRetryable() bool
@intent advertise retry-safe semantics for transient connection failures.
func (*ConnectionProblemError) Unwrap ¶
func (e *ConnectionProblemError) Unwrap() error
@intent expose the embedded TraceError to standard Go error traversal.
type Contextualizer ¶
type Contextualizer struct {
// contains filtered or unexported fields
}
@intent bundle one context's trace metadata and cancellation hooks for reuse across multiple operations. Contextualizer wraps operations with context-aware error handling
func NewContextualizer ¶
func NewContextualizer(ctx context.Context) *Contextualizer
@intent create a helper that consistently applies one context's trace metadata across multiple operations. @ensures returns a Contextualizer bound to the provided context. NewContextualizer creates a new Contextualizer
func (*Contextualizer) Do ¶
func (c *Contextualizer) Do(fn func() error) error
@intent run a function and automatically enrich any resulting error with the contextualizer's trace metadata. @ensures returns nil when the function succeeds. Do executes a function and wraps any error with context
func (*Contextualizer) OnCancel ¶
func (c *Contextualizer) OnCancel(fn func()) func() bool
@intent register cleanup or follow-up work that should run when the contextualizer's context is canceled. @sideEffect schedules a callback with the underlying context cancellation machinery. @ensures returns a stop function that can prevent the callback before cancellation. OnCancel registers fn to run after the context is canceled (Go 1.21+). Returns a stop function that prevents fn from running if called before cancellation.
type ErrorAccessDenied ¶
@intent let callers recognize authorization failure semantics through behavior instead of concrete error types. ErrorAccessDenied indicates access was denied
type ErrorAlreadyExists ¶
@intent let callers recognize duplicate-resource semantics through behavior instead of concrete error types. ErrorAlreadyExists indicates a resource already exists
type ErrorBadParameter ¶
@intent let callers recognize invalid-input semantics through behavior instead of concrete error types. ErrorBadParameter indicates invalid input parameters
type ErrorCanceled ¶
@intent let callers recognize cancellation semantics through behavior rather than concrete types. ErrorCanceled is an interface for canceled errors
type ErrorConflict ¶
@intent let callers recognize state-conflict semantics through behavior instead of concrete error types. ErrorConflict indicates a conflict occurred
type ErrorConnectionProblem ¶
@intent let callers recognize transport-failure semantics through behavior instead of concrete error types. ErrorConnectionProblem indicates a connection issue
type ErrorHandler ¶
@intent adapt slog handlers so error attributes are rewritten into the package's trace-aware schema. ErrorHandler wraps an slog.Handler to automatically extract trace information
func NewErrorHandler ¶
func NewErrorHandler(h slog.Handler) *ErrorHandler
@intent wrap slog handlers so error attributes are consistently expanded into trace-aware structure. @domainRule nil handlers fall back to slog.DiscardHandler for safe optional logging. @ensures always returns a non-nil ErrorHandler. NewErrorHandler creates a new ErrorHandler wrapping the given handler
func (*ErrorHandler) Enabled ¶
@intent defer level checks to the wrapped handler so logging enablement stays consistent. @ensures returns the wrapped handler's enabled decision unchanged.
func (*ErrorHandler) Handle ¶
@intent rewrite incoming slog records so embedded error attributes use the trace logging schema. @sideEffect creates a replacement slog.Record and forwards it to the wrapped handler. @ensures non-error attributes are preserved verbatim.
func (*ErrorHandler) WithAttrs ¶
func (h *ErrorHandler) WithAttrs(attrs []slog.Attr) slog.Handler
@intent preserve trace-aware error rewriting when callers derive a handler with additional attributes. @ensures returns another ErrorHandler wrapping the derived handler. WithAttrs returns a new handler with the given attributes
func (*ErrorHandler) WithGroup ¶
func (h *ErrorHandler) WithGroup(name string) slog.Handler
@intent preserve trace-aware error rewriting when callers derive a grouped handler. @ensures returns another ErrorHandler wrapping the grouped handler. WithGroup returns a new handler with the given group name
type ErrorLimitExceeded ¶
@intent let callers recognize throttling or quota semantics through behavior instead of concrete error types. ErrorLimitExceeded indicates a rate limit or quota was exceeded
type ErrorNotFound ¶
@intent let callers recognize missing-resource semantics through behavior instead of concrete error types. ErrorNotFound indicates a resource was not found
type ErrorNotImplemented ¶
@intent let callers recognize unsupported-operation semantics through behavior instead of concrete error types. ErrorNotImplemented indicates functionality is not implemented
type ErrorRetryable ¶
@intent let callers recognize retry-safe failures through behavior instead of concrete error types. ErrorRetryable indicates an error that can be retried
type ErrorTimeout ¶
@intent let callers recognize timeout semantics through behavior instead of concrete error types. ErrorTimeout indicates an operation timed out
type ErrorUnauthenticated ¶
@intent let callers distinguish authentication failures from authorization failures. ErrorUnauthenticated indicates authentication is missing or invalid.
type Frame ¶
type Frame struct {
// contains filtered or unexported fields
}
@intent describe one recorded call site so errors and logs can point back to their origin. @domainRule only the program counter is stored; symbol resolution is deferred to render time because errors are created far more often than they are printed. Frame represents a single stack frame. It records the call site as a program counter and resolves the function name, file, and line lazily.
func CaptureFrame ¶
@intent capture the caller information that anchors trace output to a concrete source location. @intent let packages outside this module mint errors whose first frame points at their own caller. @ensures returns an empty frame when runtime caller information is unavailable. CaptureFrame captures a single stack frame at the given skip level.
skip follows runtime.Caller: 0 is CaptureFrame itself, 1 is its immediate caller, and 2 is the caller of that function. Constructors that want the frame to point at their own caller pass 2.
func (Frame) MarshalJSON ¶
@intent keep the frame's JSON wire shape stable while the in-memory layout stays a bare program counter. @ensures emits the {"function":...,"file":...,"line":...} object shape used by earlier versions. MarshalJSON implements json.Marshaler.
type Frames ¶
type Frames []Frame
@intent represent an ordered stack trace that can be rendered or serialized with an error. Frames is a slice of stack frames
func GetFrames ¶
@intent expose captured stack frames for diagnostics without leaking mutable internal state. @ensures returns a defensive copy of the stored frames when trace data exists. GetFrames extracts frames from an error if available. Returns a copy of the frames to prevent external mutation.
type LimitExceededError ¶
type LimitExceededError struct {
*TraceError
}
@intent mark throttling or quota failures so callers can apply backoff behavior. LimitExceededError represents a rate limit or quota exceeded error
func (*LimitExceededError) Error ¶
func (e *LimitExceededError) Error() string
@intent delegate user-facing string rendering to the embedded TraceError.
func (*LimitExceededError) IsLimitExceeded ¶
func (e *LimitExceededError) IsLimitExceeded() bool
@intent advertise throttling semantics for behavior-based error checks.
func (*LimitExceededError) IsRetryable ¶
func (e *LimitExceededError) IsRetryable() bool
@intent advertise retry-safe semantics for throttled operations.
func (*LimitExceededError) Unwrap ¶
func (e *LimitExceededError) Unwrap() error
@intent expose the embedded TraceError to standard Go error traversal.
type NotFoundError ¶
type NotFoundError struct {
*TraceError
}
@intent mark failures caused by missing resources so callers can branch on lookup semantics. NotFoundError represents a "not found" error
func (*NotFoundError) Error ¶
func (e *NotFoundError) Error() string
@intent delegate user-facing string rendering to the embedded TraceError.
func (*NotFoundError) IsNotFound ¶
func (e *NotFoundError) IsNotFound() bool
@intent advertise missing-resource semantics for behavior-based error checks.
func (*NotFoundError) LogValue ¶
func (e *NotFoundError) LogValue() slog.Value
@intent reuse TraceError structured logging output for not-found errors.
func (*NotFoundError) Unwrap ¶
func (e *NotFoundError) Unwrap() error
@intent expose the embedded TraceError to standard Go error traversal.
type NotImplementedError ¶
type NotImplementedError struct {
*TraceError
}
@intent mark code paths that are recognized but intentionally unsupported. NotImplementedError represents a "not implemented" error
func (*NotImplementedError) Error ¶
func (e *NotImplementedError) Error() string
@intent delegate user-facing string rendering to the embedded TraceError.
func (*NotImplementedError) IsNotImplemented ¶
func (e *NotImplementedError) IsNotImplemented() bool
@intent advertise unsupported-operation semantics for behavior-based error checks.
func (*NotImplementedError) Unwrap ¶
func (e *NotImplementedError) Unwrap() error
@intent expose the embedded TraceError to standard Go error traversal.
type Pipeline ¶
type Pipeline[T any] struct { // contains filtered or unexported fields }
@intent model stepwise transformations that should stop automatically after the first failure. Pipeline allows chaining operations that may fail
func NewPipeline ¶
@intent start a chain of trace-aware transformations from an initial value. @ensures returns a pipeline with no initial error. NewPipeline creates a new pipeline with an initial value
func TransformPipeline ¶
@intent continue a pipeline while changing the value type and preserving trace-aware failure handling. @ensures carries forward existing pipeline errors without invoking fn. TransformPipeline transforms between different types
func (*Pipeline[T]) Recover ¶
@intent give failed pipelines a chance to replace their error with a recovery value or new error. @ensures calls fn only when the pipeline is currently failed. Recover attempts to recover from an error
func (*Pipeline[T]) RecoverWith ¶
@intent replace a failed pipeline with a caller-provided default value. @ensures clears the stored error when recovery is applied. RecoverWith recovers with a default value
func (*Pipeline[T]) Result ¶
@intent expose the pipeline state as a conventional Go value-plus-error pair. @ensures returns the current pipeline value and error unchanged. Result returns the final value and error
func (*Pipeline[T]) Then ¶
@intent apply the next transformation only while the pipeline remains successful. @ensures wraps new step failures with trace context before storing them. Then executes the function if no error has occurred
type Result ¶
type Result[T any] struct { // contains filtered or unexported fields }
@intent model success and failure as one value so callers can compose operations without losing trace context. Result represents either a value or an error (similar to Rust's Result)
Example ¶
package main
import (
"fmt"
"os"
"github.com/tae2089/trace/v2"
)
func main() {
result := trace.Try(os.Open("nonexistent.txt"))
value := result.UnwrapOr(nil)
if value == nil {
fmt.Println("File not found, using default")
}
}
Output: File not found, using default
func Collect ¶
@intent combine many Result values into one collection while preserving all failures. @domainRule any failed input produces an aggregated error instead of a partial success. Collect collects multiple Results into a single Result containing a slice
func Err ¶
@intent convert a failure into a Result while preserving trace metadata for downstream composition. @ensures wraps the provided error with trace context before storing it. Err creates a failed Result
func ErrMsg ¶
@intent create a failed Result directly from an application message when no underlying error exists. @ensures records the current call site as the first trace frame. ErrMsg creates a failed Result with a message
func FlatMap ¶
@intent chain operations that already return Result values without manual error branching. @ensures skips fn and preserves the existing error when the Result is failed. FlatMap chains Result-returning operations
func Map ¶
@intent transform successful results while leaving failures untouched. @ensures preserves the existing error without calling fn when the Result is failed. Map transforms the value if present
func MapErr ¶
@intent rewrite failure values without changing successful payloads. @ensures leaves successful results unchanged. MapErr transforms the error if present
func Ok ¶
@intent wrap a successful value in the Result abstraction without adding trace overhead. @ensures returns a Result with no error. Ok creates a successful Result
func Try ¶
@intent lift ordinary Go return pairs into a Result for composable error handling. @ensures wraps non-nil errors with trace context before storing them. Try wraps a function call that returns (T, error) into a Result
func (Result[T]) Error ¶
@intent expose the failure component directly for interoperability with Go error handling. @ensures returns nil for successful results. Error returns the error if present
func (Result[T]) IsErr ¶
@intent let callers branch on failure without unpacking the Result payload. @ensures returns true only when the Result holds an error. IsErr returns true if the Result contains an error
func (Result[T]) IsOk ¶
@intent let callers branch on success without unpacking the Result payload. @ensures returns true only when the Result holds no error. IsOk returns true if the Result contains a value
func (Result[T]) Unwrap ¶
func (r Result[T]) Unwrap() T
@intent extract the successful value in contexts where failure should abort immediately. @domainRule panics with the stored error when the Result is failed. Unwrap returns the value or panics if there's an error
func (Result[T]) UnwrapOr ¶
func (r Result[T]) UnwrapOr(defaultVal T) T
@intent provide a fallback value when the Result is failed. @ensures returns the stored value on success and the provided default on failure. UnwrapOr returns the value or the provided default
func (Result[T]) UnwrapOrElse ¶
@intent derive a fallback value from the failure reason when the Result is failed. @ensures calls the fallback function only when the Result holds an error. UnwrapOrElse returns the value or calls the function to get a default
type TimeoutError ¶
type TimeoutError struct {
*TraceError
}
@intent mark operations that exceeded their allowed completion window. TimeoutError represents a timeout error
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
@intent delegate user-facing string rendering to the embedded TraceError.
func (*TimeoutError) IsRetryable ¶
func (e *TimeoutError) IsRetryable() bool
@intent advertise retry-safe semantics for timeout failures.
func (*TimeoutError) IsTimeout ¶
func (e *TimeoutError) IsTimeout() bool
@intent advertise timeout semantics for behavior-based error checks.
func (*TimeoutError) Unwrap ¶
func (e *TimeoutError) Unwrap() error
@intent expose the embedded TraceError to standard Go error traversal.
type TraceError ¶
type TraceError struct {
// Original error being wrapped
Err error
// Message is additional context
Message string
// Frames contains the stack trace
Frames Frames
// Fields contains structured data for logging
Fields map[string]any
}
@intent serve as the canonical trace-aware error wrapper carrying cause, message, frames, and structured fields. TraceError is the core error type that captures stack traces
func (*TraceError) Error ¶
func (e *TraceError) Error() string
@intent produce the primary human-readable message for traced errors and their wrapped causes. @ensures includes frame and cause information when available. Error implements the error interface
func (*TraceError) Format ¶
func (e *TraceError) Format(s fmt.State, verb rune)
@intent support concise and verbose formatting styles for traced errors. @ensures %+v output includes stack frames and structured fields when present. Format implements fmt.Formatter for customizable output
func (*TraceError) LogValue ¶
func (e *TraceError) LogValue() slog.Value
@intent serialize traced errors into structured slog fields without losing cause or stack context. @ensures includes message, cause, trace, and fields only when those values are present. LogValue implements slog.LogValuer for structured logging. Schema: {"message":..., "cause":..., "trace":[{"file":..., "line":..., "func":...}], "fields":{...}}
func (*TraceError) Unwrap ¶
func (e *TraceError) Unwrap() error
@intent expose the wrapped cause so traced errors participate in standard Go error traversal. @ensures returns the original wrapped error. Unwrap implements the errors.Unwrap interface for Go 1.13+
type TraceErrorReplacer ¶
type TraceErrorReplacer interface {
ReplaceTraceError(original, replacement *TraceError) (rebuilt error, ok bool)
}
@intent let custom wrapper types survive field updates instead of being peeled away. @domainRule the wrapper must return ok=false when original is not its direct inner TraceError. TraceErrorReplacer lets wrapper types outside this package survive WithField and WithFields. When those functions rebuild an error chain they replace the inner *TraceError; wrappers this package does not know are otherwise dropped. A wrapper that implements this method is asked to rebuild itself around replacement and report ok=true, or ok=false if original is not its inner TraceError.
type UnauthenticatedError ¶
type UnauthenticatedError struct {
*TraceError
}
@intent mark authentication failures independently from authorization failures. UnauthenticatedError represents a missing or invalid authentication identity.
func (*UnauthenticatedError) Error ¶
func (e *UnauthenticatedError) Error() string
@intent delegate developer-facing rendering to the embedded TraceError.
func (*UnauthenticatedError) IsUnauthenticated ¶
func (e *UnauthenticatedError) IsUnauthenticated() bool
@intent advertise authentication-failure semantics for behavior-based checks.
func (*UnauthenticatedError) Unwrap ¶
func (e *UnauthenticatedError) Unwrap() error
@intent expose the embedded TraceError to standard Go error traversal.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
@index Client-side example for safely restoring typed trace errors from public HTTP error responses.
|
@index Client-side example for safely restoring typed trace errors from public HTTP error responses. |
|
@index HTTP adapters that translate trace errors into API responses, middleware behavior, and client-side classifications.
|
@index HTTP adapters that translate trace errors into API responses, middleware behavior, and client-side classifications. |