Documentation
¶
Index ¶
- Variables
- func AsError[T error](err error) (T, bool)
- func Errorf(format string, args ...any) error
- func FrameSkip(file string, fun string)
- func GetPublic(err error, defaultPublicMessage string) string
- func Join(e ...error) error
- func New(message string) error
- func Recover(cb func()) (err error)
- func Recoverf(cb func(), msg string, args ...any) (err error)
- func WithBuilder(ctx context.Context, builder OopsErrorBuilder) context.Context
- func Wrap(err error) error
- func Wrap2[A any](a A, err error) (A, error)
- func Wrap3[A any, B any](a A, b B, err error) (A, B, error)
- func Wrap4[A any, B any, C any](a A, b B, c C, err error) (A, B, C, error)
- func Wrap5[A any, B any, C any, D any](a A, b B, c C, d D, err error) (A, B, C, D, error)
- func Wrap6[A any, B any, C any, D any, E any](a A, b B, c C, d D, e E, err error) (A, B, C, D, E, error)
- func Wrap7[A any, B any, C any, D any, E any, F any](a A, b B, c C, d D, e E, f F, err error) (A, B, C, D, E, F, error)
- func Wrap8[A any, B any, C any, D any, E any, F any, G any](a A, b B, c C, d D, e E, f F, g G, err error) (A, B, C, D, E, F, G, error)
- func Wrap9[A any, B any, C any, D any, E any, F any, G any, H any](a A, b B, c C, d D, e E, f F, g G, h H, err error) (A, B, C, D, E, F, G, H, error)
- func Wrap10[A any, B any, C any, D any, E any, F any, G any, H any, I any](a A, b B, c C, d D, e E, f F, g G, h H, i I, err error) (A, B, C, D, E, F, G, H, I, error)
- func Wrapf(err error, format string, args ...any) error
- func Wrapf2[A any](a A, err error, format string, args ...any) (A, error)
- func Wrapf3[A any, B any](a A, b B, err error, format string, args ...any) (A, B, error)
- func Wrapf4[A any, B any, C any](a A, b B, c C, err error, format string, args ...any) (A, B, C, error)
- func Wrapf5[A any, B any, C any, D any](a A, b B, c C, d D, err error, format string, args ...any) (A, B, C, D, error)
- func Wrapf6[A any, B any, C any, D any, E any](a A, b B, c C, d D, e E, err error, format string, args ...any) (A, B, C, D, E, error)
- func Wrapf7[A any, B any, C any, D any, E any, F any](a A, b B, c C, d D, e E, f F, err error, format string, args ...any) (A, B, C, D, E, F, error)
- func Wrapf8[A any, B any, C any, D any, E any, F any, G any](a A, b B, c C, d D, e E, f F, g G, err error, format string, args ...any) (A, B, C, D, E, F, G, error)
- func Wrapf9[A any, B any, C any, D any, E any, F any, G any, H any](a A, b B, c C, d D, e E, f F, g G, h H, err error, format string, args ...any) (A, B, C, D, E, F, G, H, error)
- func Wrapf10[A any, B any, C any, D any, E any, F any, G any, H any, I any](a A, b B, c C, d D, e E, f F, g G, h H, i I, err error, format string, ...) (A, B, C, D, E, F, G, H, I, error)
- type OopsError
- func (o OopsError) Code() any
- func (o OopsError) Context() map[string]any
- func (o OopsError) Domain() string
- func (o OopsError) Duration() time.Duration
- func (o OopsError) Error() string
- func (o OopsError) Format(s fmt.State, verb rune)
- func (o OopsError) HasTag(tag string) bool
- func (o OopsError) Hint() string
- func (o OopsError) Is(err error) bool
- func (o OopsError) Layers() []*OopsErrorLayer
- func (o OopsError) LogValue() slog.Value
- func (o OopsError) LogValuer() slog.Valuedeprecated
- func (o OopsError) MarshalJSON() ([]byte, error)
- func (o OopsError) Owner() string
- func (o OopsError) Public() string
- func (o OopsError) Request() *http.Request
- func (o OopsError) Response() *http.Response
- func (o OopsError) Sources() string
- func (o OopsError) Span() string
- func (o OopsError) StackFrames() []runtime.Frame
- func (o OopsError) Stacktrace() string
- func (o OopsError) Tags() []string
- func (o OopsError) Tenant() (string, map[string]any)
- func (o OopsError) Time() time.Time
- func (o OopsError) ToMap() map[string]any
- func (o OopsError) Trace() string
- func (o OopsError) Unwrap() error
- func (o OopsError) User() (string, map[string]any)
- type OopsErrorBuilder
- func Assert(condition bool) OopsErrorBuilder
- func Assertf(condition bool, msg string, args ...any) OopsErrorBuilder
- func CallerSkip(skip int) OopsErrorBuilder
- func Code(code any) OopsErrorBuilder
- func Duration(duration time.Duration) OopsErrorBuilder
- func FromContext(ctx context.Context) OopsErrorBuilder
- func Hint(hint string) OopsErrorBuilder
- func In(domain string) OopsErrorBuilder
- func Owner(owner string) OopsErrorBuilder
- func Public(public string) OopsErrorBuilder
- func Request(req *http.Request, withBody bool) OopsErrorBuilder
- func Response(res *http.Response, withBody bool) OopsErrorBuilder
- func Since(time time.Time) OopsErrorBuilder
- func Span(span string) OopsErrorBuilder
- func Tags(tags ...string) OopsErrorBuilder
- func Tenant(tenantID string, data ...any) OopsErrorBuilder
- func Time(time time.Time) OopsErrorBuilder
- func Trace(trace string) OopsErrorBuilder
- func User(userID string, data ...any) OopsErrorBuilder
- func With(kv ...any) OopsErrorBuilder
- func WithContext(ctx context.Context, keys ...any) OopsErrorBuilder
- func (b OopsErrorBuilder) Assert(condition bool) OopsErrorBuilder
- func (b OopsErrorBuilder) Assertf(condition bool, msg string, args ...any) OopsErrorBuilder
- func (b OopsErrorBuilder) CallerSkip(skip int) OopsErrorBuilder
- func (b OopsErrorBuilder) Code(code any) OopsErrorBuilder
- func (b OopsErrorBuilder) Duration(duration time.Duration) OopsErrorBuilder
- func (b OopsErrorBuilder) Errorf(format string, args ...any) error
- func (b OopsErrorBuilder) Hint(hint string) OopsErrorBuilder
- func (b OopsErrorBuilder) In(domain string) OopsErrorBuilder
- func (b OopsErrorBuilder) Join(e ...error) error
- func (b OopsErrorBuilder) New(message string) error
- func (b OopsErrorBuilder) Owner(owner string) OopsErrorBuilder
- func (b OopsErrorBuilder) Public(public string) OopsErrorBuilder
- func (b OopsErrorBuilder) Recover(cb func()) (err error)
- func (b OopsErrorBuilder) Recoverf(cb func(), msg string, args ...any) (err error)
- func (b OopsErrorBuilder) Request(req *http.Request, withBody bool) OopsErrorBuilder
- func (b OopsErrorBuilder) Response(res *http.Response, withBody bool) OopsErrorBuilder
- func (b OopsErrorBuilder) Since(t time.Time) OopsErrorBuilder
- func (b OopsErrorBuilder) Span(span string) OopsErrorBuilder
- func (b OopsErrorBuilder) Tags(tags ...string) OopsErrorBuilder
- func (b OopsErrorBuilder) Tenant(tenantID string, tenantData ...any) OopsErrorBuilder
- func (b OopsErrorBuilder) Time(t time.Time) OopsErrorBuilder
- func (b OopsErrorBuilder) Trace(traceID string) OopsErrorBuilder
- func (b OopsErrorBuilder) User(userID string, userData ...any) OopsErrorBuilder
- func (b OopsErrorBuilder) With(kv ...any) OopsErrorBuilder
- func (b OopsErrorBuilder) WithContext(ctx context.Context, keys ...any) OopsErrorBuilder
- func (b OopsErrorBuilder) Wrap(err error) error
- func (b OopsErrorBuilder) Wrapf(err error, format string, args ...any) error
- type OopsErrorLayer
Constants ¶
This section is empty.
Variables ¶
var ( // SourceFragmentsHidden controls whether source code fragments are included in error output. // When true, source code context around error locations is hidden to reduce output size. SourceFragmentsHidden = true // DereferencePointers controls whether pointer values in error context are automatically // dereferenced when converting to map representations. This can be useful for logging // but may cause issues with nil pointers. DereferencePointers = true // Local specifies the timezone used for error timestamps. Defaults to UTC. Local *time.Location = time.UTC // AutoTraceID controls whether a ULID-based trace ID is automatically generated // when an error is created without an explicit trace. // // Note: this flag does not integrate with or take precedence over external tracing // systems (OpenTelemetry, HTTP middleware, etc.). Trace IDs from those systems must // still be injected explicitly via .Trace("id"). // // Generating a trace ID on every error creation has a non-negligible cost (ULID // generation + allocation). Consider setting this to false at program start when // trace IDs are always provided by an external system. AutoTraceID = true )
Global configuration variables that control the behavior of error handling.
var ( // StackTraceMaxDepth controls the maximum number of stack frames // to capture in a stack trace. This prevents stack traces from // becoming excessively long while still providing sufficient // context for debugging. // // The default value of 10 provides a good balance between // detail and readability. For deep call stacks, this will // capture the most recent 10 frames, which typically include // the most relevant debugging information. StackTraceMaxDepth = 10 )
Global configuration for stack trace generation.
Functions ¶
func AsError ¶ added in v1.22.0
AsError is a generic helper equivalent to errors.As, without requiring the caller to declare a typed variable first.
Example usage:
if myErr, ok := oops.AsError[*MyError](err); ok {
// use myErr directly
}
func FrameSkip ¶ added in v1.22.0
FrameSkip registers a frame filter that excludes matching frames from stack trace output. Both file and fun are matched using strings.Contains against the raw values returned by runtime.CallersFrames — the absolute file path and the fully-qualified function name respectively. An empty string matches anything (i.e., acts as a wildcard).
Filtering is applied at output time (when Stacktrace(), Sources(), or StackFrames() is called), not at error creation time. This means patterns registered after an error is created will still filter frames from that error's stack trace.
Calling FrameSkip with the same (file, fun) pair more than once is a no-op — duplicate entries are silently ignored.
Example:
oops.FrameSkip("myproject/pkg/errutil", "") // match by file path substring
oops.FrameSkip("", "myproject/pkg/errutil.WrapErr") // match by full function name substring
func GetPublic ¶
GetPublic returns a message that is safe to show to an end user, or a default generic message.
func Recover ¶
func Recover(cb func()) (err error)
Recover handle panic and returns `oops.OopsError` object that satisfies `error`.
func Recoverf ¶
Recoverf handle panic and returns `oops.OopsError` object that satisfies `error` and formats an error message.
func WithBuilder ¶
func WithBuilder(ctx context.Context, builder OopsErrorBuilder) context.Context
WithBuilder stores an OopsErrorBuilder in a Go context for later retrieval. This function creates a new context with the builder stored under the package's internal key, allowing the builder to be accessed by subsequent middleware or handlers in the request chain.
This is particularly useful in web applications where you want to propagate error context (like request IDs, user information, or tracing data) through the entire request processing pipeline without explicitly passing the builder to every function.
The original context is not modified; a new context is returned with the builder added. This follows Go's context immutability pattern.
Example usage:
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Create a builder with request-specific context
builder := oops.
Trace(r.Header.Get("X-Request-ID")).
With("user_agent", r.UserAgent())
// Store the builder in the request context
ctx := oops.WithBuilder(r.Context(), builder)
// Pass the enhanced context to the next handler
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func handler(w http.ResponseWriter, r *http.Request) {
// Retrieve the builder from context and create an error
err := oops.FromContext(r.Context()).
In("handler").
Errorf("something went wrong")
// The error will automatically include the trace ID and user agent
// that were set in the middleware
}
func Wrap2 ¶
Wrap2 wraps an error while preserving a single return value. This function is useful for functions that return (value, error) pairs and need the error to be wrapped with oops error handling.
The function takes a value of any type A and an error, wraps the error using oops.Wrap, and returns the original value along with the wrapped error.
Example usage:
func getUser(id string) (User, error) {
user, err := database.GetUser(id)
return oops.Wrap2(user, err)
}
// Equivalent to:
func getUser(id string) (User, error) {
user, err := database.GetUser(id)
if err != nil {
return user, oops.Wrap(err)
}
return user, nil
}
func Wrap3 ¶
Wrap3 wraps an error while preserving two return values. This function is useful for functions that return (value1, value2, error) and need the error to be wrapped with oops error handling.
The function takes two values of any types A and B and an error, wraps the error using oops.Wrap, and returns the original values along with the wrapped error.
Example usage:
func getUserAndProfile(id string) (User, Profile, error) {
user, profile, err := database.GetUserAndProfile(id)
return oops.Wrap3(user, profile, err)
}
func Wrap4 ¶
Wrap4 wraps an error while preserving three return values. This function is useful for functions that return (value1, value2, value3, error) and need the error to be wrapped with oops error handling.
The function takes three values of any types A, B, and C and an error, wraps the error using oops.Wrap, and returns the original values along with the wrapped error.
Example usage:
func getUserProfileAndSettings(id string) (User, Profile, Settings, error) {
user, profile, settings, err := database.GetUserProfileAndSettings(id)
return oops.Wrap4(user, profile, settings, err)
}
func Wrap5 ¶
Wrap5 wraps an error while preserving four return values. This function is useful for functions that return (value1, value2, value3, value4, error) and need the error to be wrapped with oops error handling.
The function takes four values of any types A, B, C, and D and an error, wraps the error using oops.Wrap, and returns the original values along with the wrapped error.
func Wrap6 ¶
func Wrap6[A any, B any, C any, D any, E any](a A, b B, c C, d D, e E, err error) (A, B, C, D, E, error)
Wrap6 wraps an error while preserving five return values. This function is useful for functions that return (value1, value2, value3, value4, value5, error) and need the error to be wrapped with oops error handling.
The function takes five values of any types A, B, C, D, and E and an error, wraps the error using oops.Wrap, and returns the original values along with the wrapped error.
func Wrap7 ¶
func Wrap7[A any, B any, C any, D any, E any, F any](a A, b B, c C, d D, e E, f F, err error) (A, B, C, D, E, F, error)
Wrap7 wraps an error while preserving six return values. This function is useful for functions that return (value1, value2, value3, value4, value5, value6, error) and need the error to be wrapped with oops error handling.
The function takes six values of any types A, B, C, D, E, and F and an error, wraps the error using oops.Wrap, and returns the original values along with the wrapped error.
func Wrap8 ¶
func Wrap8[A any, B any, C any, D any, E any, F any, G any](a A, b B, c C, d D, e E, f F, g G, err error) (A, B, C, D, E, F, G, error)
Wrap8 wraps an error while preserving seven return values. This function is useful for functions that return (value1, value2, value3, value4, value5, value6, value7, error) and need the error to be wrapped with oops error handling.
The function takes seven values of any types A, B, C, D, E, F, and G and an error, wraps the error using oops.Wrap, and returns the original values along with the wrapped error.
func Wrap9 ¶
func Wrap9[A any, B any, C any, D any, E any, F any, G any, H any](a A, b B, c C, d D, e E, f F, g G, h H, err error) (A, B, C, D, E, F, G, H, error)
Wrap9 wraps an error while preserving eight return values. This function is useful for functions that return (value1, value2, value3, value4, value5, value6, value7, value8, error) and need the error to be wrapped with oops error handling.
The function takes eight values of any types A, B, C, D, E, F, G, and H and an error, wraps the error using oops.Wrap, and returns the original values along with the wrapped error.
func Wrap10 ¶
func Wrap10[A any, B any, C any, D any, E any, F any, G any, H any, I any](a A, b B, c C, d D, e E, f F, g G, h H, i I, err error) (A, B, C, D, E, F, G, H, I, error)
Wrap10 wraps an error while preserving nine return values. This function is useful for functions that return (value1, value2, value3, value4, value5, value6, value7, value8, value9, error) and need the error to be wrapped with oops error handling.
The function takes nine values of any types A, B, C, D, E, F, G, H, and I and an error, wraps the error using oops.Wrap, and returns the original values along with the wrapped error.
func Wrapf ¶
Wrapf wraps an error into an `oops.OopsError` object that satisfies `error` and formats an error message.
func Wrapf2 ¶
Wrapf2 wraps an error with a formatted message while preserving a single return value. This function is similar to Wrap2 but uses oops.Wrapf to add additional context to the error message.
The function takes a value of any type A, an error, and a format string with arguments, wraps the error using oops.Wrapf, and returns the original value along with the wrapped error.
Example usage:
func getUser(id string) (User, error) {
user, err := database.GetUser(id)
return oops.Wrapf2(user, err, "failed to get user with id %s", id)
}
func Wrapf3 ¶
Wrapf3 wraps an error with a formatted message while preserving two return values. This function is similar to Wrap3 but uses oops.Wrapf to add additional context to the error message.
The function takes two values of any types A and B, an error, and a format string with arguments, wraps the error using oops.Wrapf, and returns the original values along with the wrapped error.
Example usage:
func getUserAndProfile(id string) (User, Profile, error) {
user, profile, err := database.GetUserAndProfile(id)
return oops.Wrapf3(user, profile, err, "failed to get user and profile for id %s", id)
}
func Wrapf4 ¶
func Wrapf4[A any, B any, C any](a A, b B, c C, err error, format string, args ...any) (A, B, C, error)
Wrapf4 wraps an error with a formatted message while preserving three return values. This function is similar to Wrap4 but uses oops.Wrapf to add additional context to the error message.
The function takes three values of any types A, B, and C, an error, and a format string with arguments, wraps the error using oops.Wrapf, and returns the original values along with the wrapped error.
func Wrapf5 ¶
func Wrapf5[A any, B any, C any, D any](a A, b B, c C, d D, err error, format string, args ...any) (A, B, C, D, error)
Wrapf5 wraps an error with a formatted message while preserving four return values. This function is similar to Wrap5 but uses oops.Wrapf to add additional context to the error message.
The function takes four values of any types A, B, C, and D, an error, and a format string with arguments, wraps the error using oops.Wrapf, and returns the original values along with the wrapped error.
func Wrapf6 ¶
func Wrapf6[A any, B any, C any, D any, E any](a A, b B, c C, d D, e E, err error, format string, args ...any) (A, B, C, D, E, error)
Wrapf6 wraps an error with a formatted message while preserving five return values. This function is similar to Wrap6 but uses oops.Wrapf to add additional context to the error message.
The function takes five values of any types A, B, C, D, and E, an error, and a format string with arguments, wraps the error using oops.Wrapf, and returns the original values along with the wrapped error.
func Wrapf7 ¶
func Wrapf7[A any, B any, C any, D any, E any, F any](a A, b B, c C, d D, e E, f F, err error, format string, args ...any) (A, B, C, D, E, F, error)
Wrapf7 wraps an error with a formatted message while preserving six return values. This function is similar to Wrap7 but uses oops.Wrapf to add additional context to the error message.
The function takes six values of any types A, B, C, D, E, and F, an error, and a format string with arguments, wraps the error using oops.Wrapf, and returns the original values along with the wrapped error.
func Wrapf8 ¶
func Wrapf8[A any, B any, C any, D any, E any, F any, G any](a A, b B, c C, d D, e E, f F, g G, err error, format string, args ...any) (A, B, C, D, E, F, G, error)
Wrapf8 wraps an error with a formatted message while preserving seven return values. This function is similar to Wrap8 but uses oops.Wrapf to add additional context to the error message.
The function takes seven values of any types A, B, C, D, E, F, and G, an error, and a format string with arguments, wraps the error using oops.Wrapf, and returns the original values along with the wrapped error.
func Wrapf9 ¶
func Wrapf9[A any, B any, C any, D any, E any, F any, G any, H any](a A, b B, c C, d D, e E, f F, g G, h H, err error, format string, args ...any) (A, B, C, D, E, F, G, H, error)
Wrapf9 wraps an error with a formatted message while preserving eight return values. This function is similar to Wrap9 but uses oops.Wrapf to add additional context to the error message.
The function takes eight values of any types A, B, C, D, E, F, G, and H, an error, and a format string with arguments, wraps the error using oops.Wrapf, and returns the original values along with the wrapped error.
func Wrapf10 ¶
func Wrapf10[A any, B any, C any, D any, E any, F any, G any, H any, I any](a A, b B, c C, d D, e E, f F, g G, h H, i I, err error, format string, args ...any) (A, B, C, D, E, F, G, H, I, error)
Wrapf10 wraps an error with a formatted message while preserving nine return values. This function is similar to Wrap10 but uses oops.Wrapf to add additional context to the error message.
The function takes nine values of any types A, B, C, D, E, F, G, H, and I, an error, and a format string with arguments, wraps the error using oops.Wrapf, and returns the original values along with the wrapped error.
Types ¶
type OopsError ¶
type OopsError struct {
// contains filtered or unexported fields
}
OopsError represents an enhanced error with additional contextual information. It implements the standard error interface while providing rich metadata for debugging, logging, and error handling.
func AsOops ¶
AsOops checks if an error is an oops.OopsError instance and returns it if so. This function is an alias to errors.As and provides a convenient way to type-assert errors to oops.OopsError without importing the errors package.
This function is useful when you need to access the rich metadata and context information stored in oops.OopsError instances, such as error codes, stacktraces, user information, or custom context data.
Example usage:
err := someFunction()
if oopsErr, ok := oops.AsOops(err); ok {
// Access oops-specific information
fmt.Printf("Error code: %v\n", oopsErr.Code())
fmt.Printf("Domain: %s\n", oopsErr.Domain())
fmt.Printf("Stacktrace: %s\n", oopsErr.Stacktrace())
// Check for specific tags
if oopsErr.HasTag("critical") {
// Handle critical errors differently
sendAlert(oopsErr)
}
}
// Chain with other error handling
if oopsErr, ok := oops.AsOops(err); ok && oopsErr.Code() == "database_error" {
// Handle database errors specifically
retryOperation()
}
func (OopsError) Code ¶
Code returns the error code from the deepest error in the chain. Error codes are machine-readable identifiers that can be used for programmatic error handling and cross-service error correlation.
func (OopsError) Context ¶
Context returns a flattened key-value context map from the error chain. Context from all errors in the chain is merged, with later errors taking precedence. Pointer values are dereferenced if DereferencePointers is enabled. Lazy evaluation functions are executed to get their values.
func (OopsError) Domain ¶
Domain returns the domain/feature category of the error. Returns the domain from the deepest error in the chain.
func (OopsError) Duration ¶
Duration returns the duration associated with the error. Returns the duration from the deepest error in the chain.
func (OopsError) Error ¶
Error returns the error message without additional context. This method implements the error interface. If the error wraps another error, it returns "message: wrapped_error". Otherwise, it returns just the message.
func (OopsError) Format ¶
Format implements the fmt.Formatter interface for custom formatting. Supports the following format verbs: - %v: standard error message - %+v: verbose format with stack trace and context - %#v: Go syntax representation.
func (OopsError) HasTag ¶
HasTag checks if the error or any of its wrapped errors contain the specified tag. This is useful for conditional error handling based on error categories.
func (OopsError) Hint ¶
Hint returns a debugging hint for resolving the error. Returns the hint from the deepest error in the chain.
func (OopsError) Is ¶
Is implements the errors.Is interface.
OopsError contains non-comparable fields (maps, slices), so the default equality check performed by errors.Is would panic at runtime. Identity is therefore established via the span ID, which is unique per error instance.
Note: errors.Is is designed for sentinel value matching (e.g. io.EOF). To check whether an error in the chain is an OopsError, prefer errors.As or oops.AsOops instead.
func (OopsError) Layers ¶ added in v1.22.0
func (o OopsError) Layers() []*OopsErrorLayer
Layers returns a slice of all OopsError layers in the error chain, from outermost to innermost. Each element represents one wrapping layer with its own attributes, allowing callers to inspect or select attributes from any layer rather than only the deepest one.
Only OopsError layers are included; non-OopsError errors in the chain (e.g. a plain fmt.Errorf or sentinel error at the root) are skipped. Use Unwrap() on the innermost layer to access the underlying error.
func (OopsError) LogValue ¶
LogValue returns a slog.Value representation of the error for structured logging. This method implements the slog.LogValuer interface and provides a flattened representation of the error's context and metadata suitable for logging systems.
func (OopsError) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface. This allows OopsError to be directly serialized to JSON.
func (OopsError) Owner ¶
Owner returns the name/email of the person/team responsible for handling this error. Returns the owner from the deepest error in the chain.
func (OopsError) Public ¶
Public returns a user-safe error message. Returns the public message from the deepest error in the chain.
func (OopsError) Request ¶
Request returns the associated HTTP request. Returns the request from the deepest error in the chain.
func (OopsError) Response ¶
Response returns the associated HTTP response. Returns the response from the deepest error in the chain.
func (OopsError) Sources ¶
Sources returns formatted source code fragments around the error location. This provides context about the code that caused the error, which is particularly useful for debugging. The output includes line numbers and highlights the exact line where the error occurred.
func (OopsError) Span ¶
Span returns the current span identifier. Unlike other attributes, span returns the current error's span, not the deepest one.
func (OopsError) StackFrames ¶
StackFrames returns the raw stack frames as runtime.Frame objects. This is useful for custom stack trace formatting or analysis.
func (OopsError) Stacktrace ¶
Stacktrace returns a formatted string representation of the error's stack trace. The stack trace shows the call hierarchy leading to the error, excluding frames from the Go standard library and this package. The stacktrace is basically written from the bottom to the top, in order to dedup frames. It support recursive code.
func (OopsError) Tags ¶
Tags returns all unique tags from the error chain. Tags are merged from all errors in the chain and deduplicated.
func (OopsError) Tenant ¶
Tenant returns the tenant ID and associated tenant data. Returns the tenant information from the deepest error in the chain.
func (OopsError) Time ¶
Time returns the timestamp when the error occurred. Returns the time from the deepest error in the chain.
func (OopsError) ToMap ¶
ToMap converts the error to a map representation suitable for JSON serialization. This method provides a flattened view of all error attributes and is useful for logging, debugging, and cross-service error transmission.
func (OopsError) Trace ¶
Trace returns the transaction/trace/correlation ID. An ID is auto-generated at error creation time if none was set explicitly.
Explicit traces (set via .Trace("id")) always take precedence over auto-generated ones, regardless of chain depth. Among traces of the same kind, the deepest one in the chain wins.
type OopsErrorBuilder ¶
type OopsErrorBuilder struct {
// contains filtered or unexported fields
}
OopsErrorBuilder holds the head of an immutable linked-list option chain. Each chainable method returns a new builder without modifying the receiver.
func Assert ¶
func Assert(condition bool) OopsErrorBuilder
Assert panics if condition is false. Panic payload will be of type oops.OopsError. Assertions can be chained.
func Assertf ¶
func Assertf(condition bool, msg string, args ...any) OopsErrorBuilder
Assertf panics if condition is false. Panic payload will be of type oops.OopsError. Assertions can be chained.
func CallerSkip ¶ added in v1.22.0
func CallerSkip(skip int) OopsErrorBuilder
CallerSkip sets the number of additional callers to skip when capturing the stack trace. This is useful when oops is wrapped in helper functions.
func Code ¶
func Code(code any) OopsErrorBuilder
Code set a code or slug that describes the error. Error messages are intended to be read by humans, but such code is expected to be read by machines and even transported over different services.
func Duration ¶
func Duration(duration time.Duration) OopsErrorBuilder
Duration set the error duration.
func FromContext ¶
func FromContext(ctx context.Context) OopsErrorBuilder
func Owner ¶
func Owner(owner string) OopsErrorBuilder
Owner set the name/email of the colleague/team responsible for handling this error. Useful for alerting purpose.
func Public ¶
func Public(public string) OopsErrorBuilder
Public sets a message that is safe to show to an end user.
func Request ¶
func Request(req *http.Request, withBody bool) OopsErrorBuilder
Request supplies a http.Request.
func Response ¶
func Response(res *http.Response, withBody bool) OopsErrorBuilder
Response supplies a http.Response.
func Tags ¶
func Tags(tags ...string) OopsErrorBuilder
Tags adds multiple tags, describing the feature returning an error.
func Tenant ¶
func Tenant(tenantID string, data ...any) OopsErrorBuilder
Tenant supplies a tenant id with optional attributes. Attributes can be provided as alternating string key/value pairs, map[string]any values, and slog.Attr values.
func Time ¶
func Time(time time.Time) OopsErrorBuilder
Time set the error time. Default: `time.Now()`.
func Trace ¶
func Trace(trace string) OopsErrorBuilder
Trace set a transaction id, trace id or correlation id...
func User ¶
func User(userID string, data ...any) OopsErrorBuilder
User supplies a user id with optional attributes. Attributes can be provided as alternating string key/value pairs, map[string]any values, and slog.Attr values.
func With ¶
func With(kv ...any) OopsErrorBuilder
With supplies a list of attributes declared by pair of key+value.
func WithContext ¶
func WithContext(ctx context.Context, keys ...any) OopsErrorBuilder
WithContext supplies a list of values declared in context.
func (OopsErrorBuilder) Assert ¶
func (b OopsErrorBuilder) Assert(condition bool) OopsErrorBuilder
Assert panics if the condition is false. This method provides a way to add assertions to code that will panic with an OopsError if the condition fails. The assertion can be chained with other builder methods.
Example:
oops.
Code("assertion_failed").
Assert(userID != "", "user ID cannot be empty").
Assert(email != "", "user email cannot be empty").
Assert(orgID != "", "user organization ID cannot be empty")
func (OopsErrorBuilder) Assertf ¶
func (b OopsErrorBuilder) Assertf(condition bool, msg string, args ...any) OopsErrorBuilder
Assertf panics if the condition is false with a custom message. Similar to Assert, but allows for a custom formatted message when the assertion fails.
Example:
oops.
Code("assertion_failed").
Assertf(userID != "", "user ID cannot be empty, got: %s", userID).
Assertf(email != "", "user email cannot be empty, got: %s", email).
Assertf(orgID != "", "user organization ID cannot be empty, got: %s", orgID)
func (OopsErrorBuilder) CallerSkip ¶ added in v1.22.0
func (b OopsErrorBuilder) CallerSkip(skip int) OopsErrorBuilder
CallerSkip sets the number of additional callers to skip when capturing the stack trace. This is useful when oops is wrapped in helper functions and you want the stack trace to start at the actual caller of your helper, not inside the helper itself.
func (OopsErrorBuilder) Code ¶
func (b OopsErrorBuilder) Code(code any) OopsErrorBuilder
Code sets a machine-readable error code or slug. Error codes are useful for programmatic error handling and cross-service error correlation. They should be consistent and well-documented.
Example:
oops.Code("database_connection_failed").Errorf("connection timeout")
func (OopsErrorBuilder) Duration ¶
func (b OopsErrorBuilder) Duration(duration time.Duration) OopsErrorBuilder
Duration sets the duration associated with the error. This is useful for errors that are related to timeouts or performance issues.
Example:
oops.Duration(5 * time.Second).Errorf("request timeout")
func (OopsErrorBuilder) Errorf ¶
func (b OopsErrorBuilder) Errorf(format string, args ...any) error
Errorf creates a new error with a formatted message. Similar to New, but allows for formatted messages using printf-style formatting.
Example:
err := oops.
Code("validation_error").
Errorf("invalid input: expected %s, got %s", expectedType, actualType)
func (OopsErrorBuilder) Hint ¶
func (b OopsErrorBuilder) Hint(hint string) OopsErrorBuilder
Hint provides a debugging hint for resolving the error. Hints should provide actionable guidance for developers.
Example:
oops.Hint("Check database connection and credentials").Errorf("connection failed")
func (OopsErrorBuilder) In ¶
func (b OopsErrorBuilder) In(domain string) OopsErrorBuilder
In sets the domain or feature category for the error. Domains help categorize errors by the part of the system they relate to.
Example:
oops.In("database").Errorf("connection failed")
func (OopsErrorBuilder) Join ¶
func (b OopsErrorBuilder) Join(e ...error) error
Join combines multiple errors into a single error. This method uses the standard errors.Join function to combine multiple errors while preserving the builder's context.
Example:
err := oops.
Code("multi_error").
Join(err1, err2, err3)
func (OopsErrorBuilder) New ¶
func (b OopsErrorBuilder) New(message string) error
New creates a new error with the specified message. This method creates a simple error without wrapping an existing one. The message is treated as the primary error message.
Example:
err := oops.
Code("validation_error").
New("invalid input parameters")
func (OopsErrorBuilder) Owner ¶
func (b OopsErrorBuilder) Owner(owner string) OopsErrorBuilder
Owner sets the person or team responsible for handling this error. This is useful for alerting and error routing.
Example:
oops.Owner("database-team@company.com").Errorf("connection failed")
func (OopsErrorBuilder) Public ¶
func (b OopsErrorBuilder) Public(public string) OopsErrorBuilder
Public sets a user-safe error message. This message should be safe to display to end users without exposing internal system details.
Example:
oops.Public("Unable to process your request").Errorf("internal server error")
func (OopsErrorBuilder) Recover ¶
func (b OopsErrorBuilder) Recover(cb func()) (err error)
Recover handles panics and converts them to OopsError instances. This method executes the provided callback function and catches any panics, converting them to properly formatted OopsError instances with stack traces. If the panic payload is already an error, it wraps that error. Otherwise, it creates a new error from the panic value.
Example:
err := oops.
Code("panic_recovered").
Recover(func() {
// Potentially panicking code
riskyOperation()
})
func (OopsErrorBuilder) Recoverf ¶
func (b OopsErrorBuilder) Recoverf(cb func(), msg string, args ...any) (err error)
Recoverf handles panics with additional context message. Similar to Recover, but adds a formatted message to describe the context in which the panic occurred.
Example:
err := oops.
Code("panic_recovered").
Recoverf(func() {
riskyOperation()
}, "panic in operation: %s", operationName)
func (OopsErrorBuilder) Request ¶
func (b OopsErrorBuilder) Request(req *http.Request, withBody bool) OopsErrorBuilder
Request adds HTTP request information to the error context. The withBody parameter controls whether the request body is included. Including request bodies may impact performance and memory usage.
Example:
oops.Request(req, true).Errorf("request processing failed")
func (OopsErrorBuilder) Response ¶
func (b OopsErrorBuilder) Response(res *http.Response, withBody bool) OopsErrorBuilder
Response adds HTTP response information to the error context. The withBody parameter controls whether the response body is included. Including response bodies may impact performance and memory usage.
Example:
oops.Response(res, false).Errorf("response processing failed")
func (OopsErrorBuilder) Since ¶
func (b OopsErrorBuilder) Since(t time.Time) OopsErrorBuilder
Since calculates the duration since the specified time. This is useful for measuring how long an operation took before failing.
Example:
start := time.Now()
// ... perform operation ...
oops.Since(start).Errorf("operation timed out")
func (OopsErrorBuilder) Span ¶
func (b OopsErrorBuilder) Span(span string) OopsErrorBuilder
Span sets the current span identifier. Spans represent units of work and are useful for distributed tracing.
Example:
oops.Span("database-query").Errorf("query failed")
func (OopsErrorBuilder) Tags ¶
func (b OopsErrorBuilder) Tags(tags ...string) OopsErrorBuilder
Tags adds multiple tags for categorizing the error. Tags are useful for filtering and grouping errors in monitoring systems.
Example:
oops.Tags("auth", "permission", "critical").Errorf("access denied")
func (OopsErrorBuilder) Tenant ¶
func (b OopsErrorBuilder) Tenant(tenantID string, tenantData ...any) OopsErrorBuilder
Tenant adds tenant information to the error context. This method accepts a tenant ID followed by key-value pairs for tenant data.
Example:
oops.Tenant("tenant-456", "name", "Acme Corp", "plan", "premium").Errorf("quota exceeded")
func (OopsErrorBuilder) Time ¶
func (b OopsErrorBuilder) Time(t time.Time) OopsErrorBuilder
Time sets the timestamp when the error occurred. If not set, the error will use the current time when created.
Example:
oops.Time(time.Now()).Errorf("operation failed")
func (OopsErrorBuilder) Trace ¶
func (b OopsErrorBuilder) Trace(traceID string) OopsErrorBuilder
Trace sets a transaction, trace, or correlation ID. This is useful for distributed tracing and correlating errors across services.
Example:
oops.Trace("req-123-456").Errorf("service call failed")
func (OopsErrorBuilder) User ¶
func (b OopsErrorBuilder) User(userID string, userData ...any) OopsErrorBuilder
User adds user information to the error context. This method accepts a user ID followed by key-value pairs for user data.
Example:
oops.User("user-123", "firstname", "John", "lastname", "Doe").Errorf("permission denied")
func (OopsErrorBuilder) With ¶
func (b OopsErrorBuilder) With(kv ...any) OopsErrorBuilder
With adds key-value pairs to the error context. Context values are useful for debugging and provide additional information about the error. Values can be of any type and will be serialized appropriately.
Performance: Context values are stored in a map and processed during error creation. Large numbers of context values may impact performance later, but not during error creation.
Example:
oops.With("user_id", 123, "operation", "create").Errorf("validation failed")
func (OopsErrorBuilder) WithContext ¶
func (b OopsErrorBuilder) WithContext(ctx context.Context, keys ...any) OopsErrorBuilder
WithContext extracts values from a Go context and adds them to the error context. This is useful for propagating context values through error chains.
Example:
oops.WithContext(ctx, "request_id", "user_id").Errorf("operation failed")
func (OopsErrorBuilder) Wrap ¶
func (b OopsErrorBuilder) Wrap(err error) error
Wrap wraps an existing error into an OopsError with the current builder's context. If the input error is nil, returns nil. Otherwise, creates a new OopsError that wraps the original error while preserving all the contextual information set in the builder.
Example:
err := oops.
Code("database_error").
In("database").
Wrap(originalError)
func (OopsErrorBuilder) Wrapf ¶
func (b OopsErrorBuilder) Wrapf(err error, format string, args ...any) error
Wrapf wraps an existing error with additional formatted message. Similar to Wrap, but adds a formatted message that describes the context in which the error occurred.
Example:
err := oops.
Code("database_error").
In("database").
Wrapf(originalError, "failed to execute query: %s", queryName)
type OopsErrorLayer ¶ added in v1.22.0
type OopsErrorLayer struct {
// Core error information
Code any
Time time.Time
Duration time.Duration
// Contextual information
Domain string
Tags []string
Context map[string]any
// Tracing information
Trace string
Span string
// Developer-facing information
Hint string
Public string
Owner string
// User and tenant information
UserID string
UserData map[string]any
TenantID string
TenantData map[string]any
// HTTP request/response information
Request *http.Request
Response *http.Response
}
OopsErrorLayer holds the attributes of a single layer in an error chain, as returned by Layers(). Every field reflects the value set at that specific wrapping level only — no chain traversal is performed. Fields that were not set on that layer carry their zero value.