Documentation
ΒΆ
Overview ΒΆ
Package erro provides a comprehensive error handling library for Go, offering features like error wrapping, structured logging, stack traces, and error classification. It is designed to be a drop-in replacement for the standard `errors` package, providing more context and control over error handling.
Index ΒΆ
- Constants
- Variables
- func ApplyFormatVerbs(format string, args ...any) (result string, rest []any)
- func As(err error, target any) (ok bool)
- func Close(err *error, cl io.Closer, msg string, fields ...any)
- func Fields(fields ...any) errorFields
- func FormatErrorMessage(err Error) string
- func FormatErrorWithFields(err Error) string
- func Formatter(f FormatErrorFunc) errorOpt
- func HTTPCode(err error) int
- func ID(id string) errorOpt
- func Is(err error, target error) (ok bool)
- func Join(errs ...error) error
- func LogError(err error, logFunc func(message string, fields ...any), optFuncs ...LogOption)
- func LogErrorWithOptions(err error, logFunc func(message string, fields ...any), opts LogOptions)
- func LogFields(err error, optFuncs ...LogOption) []any
- func LogFieldsMap(err error, optFuncs ...LogOption) map[string]any
- func LogFieldsMapWithOptions(err error, opts LogOptions) map[string]any
- func LogFieldsWithOptions(err error, opts LogOptions) []any
- func RecordMetrics(m ErrorMetrics) errorWork
- func RecordSpan(s TraceSpan) errorWork
- func Retryable() errorOpt
- func SendEvent(ctx context.Context, d EventDispatcher) errorWork
- func Shutdown(ctx context.Context, err *error, sd func(ctx context.Context) error, ...)
- func StackTrace(c ...*StackTraceConfig) errorOpt
- func StackTraceWithSkip(skip int, c ...*StackTraceConfig) errorOpt
- func Unwrap(err error) error
- type Error
- type ErrorCategory
- type ErrorClass
- type ErrorMetrics
- type ErrorSchema
- type ErrorSeverity
- func (s ErrorSeverity) IsCritical() bool
- func (s ErrorSeverity) IsHigh() bool
- func (s ErrorSeverity) IsInfo() bool
- func (s ErrorSeverity) IsLow() bool
- func (s ErrorSeverity) IsMedium() bool
- func (s ErrorSeverity) IsUnknown() bool
- func (s ErrorSeverity) IsValid() bool
- func (s ErrorSeverity) Label() string
- func (s ErrorSeverity) String() string
- type ErrorTemplate
- type EventDispatcher
- type FormatErrorFunc
- type KeyGetterFunc
- type List
- func (g *List) Add(err error) *List
- func (g *List) Clear() *List
- func (g *List) Copy() *List
- func (g *List) Empty() bool
- func (g *List) Err() error
- func (g *List) Errors() []error
- func (g *List) Errs() []Error
- func (g *List) First() Error
- func (g *List) Last() Error
- func (g *List) Len() int
- func (g *List) New(message string, meta ...any) *List
- func (g *List) NotEmpty() bool
- func (g *List) Remove(i int) bool
- func (g *List) RemoveError(err error) bool
- func (g *List) Wrap(err error, message string, meta ...any) *List
- type LogOption
- func MergeLogOpts(opts []LogOption, addsOpts ...LogOption) []LogOption
- func WithCategory(include ...bool) LogOption
- func WithCreatedTime(include ...bool) LogOption
- func WithErrorMessage(include ...bool) LogOption
- func WithFieldNamePrefix(prefix string) LogOption
- func WithFile(include ...bool) LogOption
- func WithFunction(include ...bool) LogOption
- func WithID(include ...bool) LogOption
- func WithLine(include ...bool) LogOption
- func WithPackage(include ...bool) LogOption
- func WithRetryable(include ...bool) LogOption
- func WithSeverity(include ...bool) LogOption
- func WithStack(include ...bool) LogOption
- func WithStackFormat(format StackFormat) LogOption
- func WithTracing(include ...bool) LogOption
- func WithUserFields(include ...bool) LogOption
- type LogOptions
- type RedactedValue
- type SafeList
- func (sl *SafeList) Add(err error) *SafeList
- func (sl *SafeList) Clear() *SafeList
- func (sl *SafeList) Copy() *SafeList
- func (sl *SafeList) Empty() bool
- func (sl *SafeList) Err() error
- func (sl *SafeList) Errors() []error
- func (sl *SafeList) Errs() []Error
- func (sl *SafeList) First() Error
- func (sl *SafeList) Last() Error
- func (sl *SafeList) Len() int
- func (sl *SafeList) New(message string, meta ...any) *SafeList
- func (sl *SafeList) NotEmpty() bool
- func (sl *SafeList) Remove(i int) bool
- func (sl *SafeList) RemoveError(err error) bool
- func (sl *SafeList) Wrap(err error, message string, meta ...any) *SafeList
- type SafeSet
- func (ss *SafeSet) Add(err error) *SafeSet
- func (ss *SafeSet) Clear() *SafeSet
- func (ss *SafeSet) Copy() *SafeSet
- func (ss *SafeSet) Empty() bool
- func (ss *SafeSet) Err() error
- func (ss *SafeSet) Errors() []error
- func (ss *SafeSet) Errs() []Error
- func (ss *SafeSet) First() Error
- func (ss *SafeSet) Last() Error
- func (ss *SafeSet) Len() int
- func (ss *SafeSet) New(message string, meta ...any) *SafeSet
- func (ss *SafeSet) NotEmpty() bool
- func (ss *SafeSet) Remove(i int) bool
- func (ss *SafeSet) RemoveError(err error) bool
- func (ss *SafeSet) WithKeyGetter(keyGetter KeyGetterFunc) *SafeSet
- func (ss *SafeSet) Wrap(err error, message string, meta ...any) *SafeSet
- type Set
- func (s *Set) Add(err error) *Set
- func (s *Set) Clear() *Set
- func (s *Set) Copy() *Set
- func (s *Set) Err() error
- func (s *Set) New(message string, meta ...any) *Set
- func (s *Set) Remove(i int) bool
- func (s *Set) RemoveError(err error) bool
- func (s *Set) WithKeyGetter(keyGetter KeyGetterFunc) *Set
- func (s *Set) Wrap(err error, message string, meta ...any) *Set
- type Stack
- func (s Stack) ContainsFunction(functionName string) bool
- func (s Stack) ExtractPackages() []string
- func (s Stack) FilterByPackage(packageName string) Stack
- func (s Stack) FormatFull() string
- func (s Stack) GetCallChain() []string
- func (s Stack) GetOriginContext() *StackContext
- func (s Stack) IsGlobalError() bool
- func (s Stack) String() string
- func (s Stack) ToJSON() []map[string]any
- func (s Stack) ToJSONUserFrames() []map[string]any
- func (s Stack) ToLogFields() map[string]any
- func (s Stack) TopUserFrame() *StackFrame
- func (s Stack) UserFrames() Stack
- type StackContext
- type StackFormat
- type StackFrame
- func (f StackFrame) FormatFull() string
- func (f StackFrame) GetContext() StackContext
- func (f StackFrame) IsErroInternal() bool
- func (f StackFrame) IsRuntime() bool
- func (f StackFrame) IsStandardLibrary() bool
- func (f StackFrame) IsTest() bool
- func (f StackFrame) IsUser() bool
- func (f StackFrame) String() string
- func (f StackFrame) ToJSON() map[string]any
- type StackTraceConfig
- type TraceSpan
Constants ΒΆ
const ( // MaxMessageLength is the maximum length for error messages. MaxMessageLength = 1000 // MaxKeyLength is the maximum length for field keys. MaxKeyLength = 128 // MaxValueLength is the maximum length for field values when converted to a string. MaxValueLength = 1024 // MaxFieldsCount is the maximum number of fields (key-value pairs). MaxFieldsCount = 100 // MaxWrapDepth is the maximum depth of error wrapping. MaxWrapDepth = 50 // MaxStackDepth is the maximum stack depth. MaxStackDepth = 50 // RedactedPlaceholder is the placeholder for redacted values. RedactedPlaceholder = "[REDACTED]" // MissingFieldPlaceholder is the placeholder for missing field values. MissingFieldPlaceholder = "<missing>" )
Security configuration constants
Variables ΒΆ
var ( // DefaultLogOptions includes a balanced set of fields for typical logging. DefaultLogOptions = LogOptions{ IncludeErrorMessage: true, IncludeUserFields: true, IncludeID: false, IncludeCategory: true, IncludeSeverity: true, IncludeTracing: true, IncludeCreatedTime: false, IncludeRetryable: true, IncludeFunction: true, IncludePackage: false, IncludeFile: false, IncludeLine: false, IncludeStack: false, StackFormat: StackFormatJSON, FieldNamePrefix: "error_", } // VerboseLogOpts is a slice of [LogOption] functions for verbose logging. VerboseLogOpts = []LogOption{ WithErrorMessage(true), WithUserFields(true), WithID(true), WithSeverity(true), WithCategory(true), WithTracing(true), WithRetryable(true), WithCreatedTime(true), WithFunction(true), WithPackage(true), WithFile(true), WithLine(true), WithStack(true), } // MinimalLogOpts is a slice of [LogOption] functions for minimal logging. MinimalLogOpts = []LogOption{ WithErrorMessage(true), WithUserFields(true), WithSeverity(true), } )
var ( // ValidationError creates a new validation error. ValidationError = NewTemplate("failed validation: %s", ClassValidation, CategoryUserInput, SeverityLow, ) // NotFoundError creates a new not found error. NotFoundError = NewTemplate("%s not found", ClassNotFound, SeverityMedium, ) // DatabaseError creates a new database error. DatabaseError = NewTemplate("database error: %s", CategoryDatabase, SeverityHigh, ) // NetworkError creates a new network error. NetworkError = NewTemplate("network error: %s", CategoryNetwork, SeverityMedium, Retryable(), ) // AuthenticationError creates a new authentication error. AuthenticationError = NewTemplate("authentication failed: %s", CategoryAuth, ClassUnauthenticated, SeverityMedium, ) // AuthorizationError creates a new authorization error. AuthorizationError = NewTemplate("permission denied: %s", CategoryAuth, ClassPermissionDenied, SeverityHigh, ) // TimeoutError creates a new timeout error. TimeoutError = NewTemplate("operation timeout: %s", ClassTimeout, SeverityLow, Retryable(), ) // ConflictError creates a new conflict error. ConflictError = NewTemplate("conflict: %s", ClassConflict, SeverityMedium, ) // RateLimitError creates a new rate limit error. RateLimitError = NewTemplate("rate limit exceeded: %s", ClassRateLimited, SeverityLow, Retryable(), ) // InternalError creates a new internal error. InternalError = NewTemplate("internal error: %s", ClassInternal, SeverityHigh, ) // SecurityError creates a new security error. SecurityError = NewTemplate("security violation: %s", ClassSecurity, CategorySecurity, SeverityCritical, ) // ExternalError creates a new external service error. ExternalError = NewTemplate("external error: %s", ClassExternal, CategoryExternal, SeverityMedium, Retryable(), ) // PaymentError creates a new payment error. PaymentError = NewTemplate("payment error: %s", CategoryPayment, SeverityCritical, Retryable(), ) // CacheError creates a new cache error. CacheError = NewTemplate("cache error: %s", CategoryCache, ClassTemporary, SeverityMedium, Retryable(), ) // ConfigError creates a new configuration error. ConfigError = NewTemplate("configuration error: %s", CategoryConfig, ClassInternal, SeverityCritical, ) // APIError creates a new API error. APIError = NewTemplate("API error: %s", CategoryAPI, SeverityHigh, ) // BusinessLogicError creates a new business logic error. BusinessLogicError = NewTemplate("business logic error: %s", CategoryBusinessLogic, SeverityHigh, ) // StorageError creates a new storage error. StorageError = NewTemplate("storage error: %s", CategoryStorage, SeverityHigh, ) // ProcessingError creates a new processing error. ProcessingError = NewTemplate("processing error: %s", CategoryProcessing, ClassInternal, SeverityHigh, ) // MonitoringError creates a new monitoring error. MonitoringError = NewTemplate("monitoring error: %s", CategoryMonitoring, SeverityMedium, ) // NotificationError creates a new notification error. NotificationError = NewTemplate("notification error: %s", CategoryNotifications, ClassTemporary, SeverityLow, ) // AIError creates a new AI/ML error. AIError = NewTemplate("AI error: %s", CategoryAI, ClassInternal, SeverityHigh, ) // AnalyticsError creates a new analytics error. AnalyticsError = NewTemplate("analytics error: %s", CategoryAnalytics, SeverityLow, ) // EventsTemplate creates a new events error. EventsTemplate = NewTemplate("events error: %s", CategoryEvents, SeverityMedium, ) // CriticalError creates a new critical error. CriticalError = NewTemplate("critical error: %s", ClassCritical, SeverityCritical, ) // TemporaryError creates a new temporary error. TemporaryError = NewTemplate("temporary error: %s", ClassTemporary, SeverityMedium, ) // DataLossError creates a new data loss error. DataLossError = NewTemplate("data loss: %s", ClassDataLoss, SeverityCritical, ) // ResourceExhaustedError creates a new resource exhausted error. ResourceExhaustedError = NewTemplate("resource exhausted: %s", ClassResourceExhausted, SeverityHigh, ) UnavailableError = NewTemplate("service unavailable: %s", ClassUnavailable, SeverityHigh, ) // CancelledError creates a new cancelled error. CancelledError = NewTemplate("operation cancelled: %s", ClassCancelled, SeverityLow, ) // NotImplementedError creates a new not implemented error. NotImplementedError = NewTemplate("not implemented: %s", ClassNotImplemented, SeverityMedium, ) // AlreadyExistsError creates a new already exists error. AlreadyExistsError = NewTemplate("already exists: %s", ClassAlreadyExists, SeverityMedium, ) )
Predefined error templates.
var ( // ErrMaxWrapDepthExceeded is a sentinel reserved for wrap-depth overflow. // // Deprecated: it is no longer returned. When the wrap depth reaches // [MaxWrapDepth], [Wrap] returns the inner error unchanged instead of // adding another layer. Kept exported for API compatibility. ErrMaxWrapDepthExceeded = New("maximum wrap depth exceeded") )
Functions ΒΆ
func ApplyFormatVerbs ΒΆ
ApplyFormatVerbs replaces format verbs in a string with arguments.
It supports a subset of package fmt syntax: optional flags '+', '-', '#', '0', an optional width and precision (each up to 4 digits), and the verbs b c d e E f F g G o O p q s t T U v x X w ('%w' is formatted like '%v'). '%%' emits a literal '%'. Anything else β the space flag, '*' width, argument indexes like '%[1]d', unknown verbs β is emitted literally and consumes no argument, so messages like "90% done" stay intact. Once arguments run out, remaining verbs are emitted literally. Unconsumed arguments are returned for use as key-value fields.
func As ΒΆ
As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true. It is a drop-in replacement for the standard `errors.As` function.
func Close ΒΆ
Close is a utility function that closes an io.Closer and wraps any resulting error. It is intended to be used in defer statements.
If the closer is nil, it does nothing. If the close operation returns an error, it will be wrapped with the provided message and fields.
Example:
func ReadData(path string) (data []byte, err error) {
f, err := os.Open(path)
if err != nil {
return nil, erro.Wrap(err, "failed to open file")
}
defer erro.Close(&err, f, "failed to close file")
// ... read data from f
}
func FormatErrorMessage ΒΆ
FormatErrorMessage formats an error with its message only.
func FormatErrorWithFields ΒΆ
FormatErrorWithFields formats an Error with its message and fields.
func Formatter ΒΆ
func Formatter(f FormatErrorFunc) errorOpt
Formatter sets a custom error message formatter.
func HTTPCode ΒΆ
HTTPCode returns an appropriate HTTP status code for a given error.
This function provides automatic HTTP status code mapping based on error classification, enabling seamless integration between your application's error handling and HTTP responses.
Error Class Mappings ΒΆ
The following error classes map to specific HTTP status codes:
ClassValidation -> 400 Bad Request ClassNotFound -> 404 Not Found ClassAlreadyExists -> 409 Conflict ClassPermissionDenied -> 403 Forbidden ClassUnauthenticated -> 401 Unauthorized ClassTimeout -> 504 Gateway Timeout ClassConflict -> 409 Conflict ClassRateLimited -> 429 Too Many Requests ClassTemporary -> 503 Service Unavailable ClassUnavailable -> 503 Service Unavailable ClassInternal -> 500 Internal Server Error ClassCancelled -> 499 Client Closed Request (non-standard) ClassNotImplemented -> 501 Not Implemented ClassSecurity -> 403 Forbidden ClassCritical -> 500 Internal Server Error ClassExternal -> 502 Bad Gateway ClassDataLoss -> 500 Internal Server Error ClassResourceExhausted -> 429 Too Many Requests
Error Category Fallback Mappings ΒΆ
When no error class is specified, categories provide fallback mappings:
CategoryUserInput -> 400 Bad Request CategoryAuth -> 401 Unauthorized CategoryDatabase -> 500 Internal Server Error CategoryNetwork -> 502 Bad Gateway CategoryAPI -> 502 Bad Gateway CategoryBusinessLogic -> 422 Unprocessable Entity CategoryCache -> 503 Service Unavailable CategoryConfig -> 500 Internal Server Error CategoryExternal -> 502 Bad Gateway CategorySecurity -> 403 Forbidden CategoryPayment -> 402 Payment Required CategoryStorage -> 507 Insufficient Storage CategoryProcessing -> 422 Unprocessable Entity CategoryAnalytics -> 500 Internal Server Error CategoryAI -> 500 Internal Server Error CategoryMonitoring -> 500 Internal Server Error CategoryNotifications -> 500 Internal Server Error CategoryEvents -> 500 Internal Server Error
Basic Usage ΒΆ
// Using error classes
err := erro.New("user not found", erro.ClassNotFound)
statusCode := erro.HTTPCode(err) // Returns 404
err := erro.New("invalid email format", erro.ClassValidation)
statusCode := erro.HTTPCode(err) // Returns 400
// Using error categories as fallback
err := erro.New("database connection failed", erro.CategoryDatabase)
statusCode := erro.HTTPCode(err) // Returns 500
REST API Error Handling ΒΆ
Build consistent REST API error responses:
// Validation errors -> 400 Bad Request
err := erro.New("validation failed",
"field", "email",
"reason", "invalid format",
erro.ClassValidation,
)
statusCode := erro.HTTPCode(err) // 400
// Authentication errors -> 401 Unauthorized
err := erro.New("invalid credentials",
"login_attempt", 3,
erro.ClassUnauthenticated,
)
statusCode := erro.HTTPCode(err) // 401
// Authorization errors -> 403 Forbidden
err := erro.New("insufficient permissions",
"required_role", "admin",
"user_role", "user",
erro.ClassPermissionDenied,
)
statusCode := erro.HTTPCode(err) // 403
// Resource not found -> 404 Not Found
err := erro.New("user not found",
"user_id", 12345,
erro.ClassNotFound,
)
statusCode := erro.HTTPCode(err) // 404
// Rate limiting -> 429 Too Many Requests
err := erro.New("rate limit exceeded",
"limit", 100,
"window", "1h",
erro.ClassRateLimited,
)
statusCode := erro.HTTPCode(err) // 429
Middleware Integration ΒΆ
Use with HTTP middleware for centralized error handling:
func ErrorMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
var httpErr error
if e, ok := err.(error); ok {
httpErr = e
} else {
httpErr = fmt.Errorf("panic: %v", err)
}
statusCode := erro.HTTPCode(httpErr)
http.Error(w, httpErr.Error(), statusCode)
}
}()
next.ServeHTTP(w, r)
})
}
Some Notes ΒΆ
- If the error is nil, it returns 200 OK - If the error is not an Error, it returns 500 Internal Server Error - If the error is an Error, it returns the appropriate HTTP status code based on the error class and category
func Is ΒΆ
Is reports whether any error in err's chain matches target. It is a drop-in replacement for the standard `errors.Is` function.
func Join ΒΆ
Join returns an error that wraps the given errors. Any nil error values are discarded. It is a drop-in replacement for the standard `errors.Join` function.
func LogError ΒΆ
LogError executes a callback with the error message and structured fields, allowing for integration with any logging library.
If the error is not an Error, it logs the error message directly.
Example:
erro.LogError(err, func(message string, fields ...any) {
myLogger.Error(message, fields...)
})
func LogErrorWithOptions ΒΆ
func LogErrorWithOptions(err error, logFunc func(message string, fields ...any), opts LogOptions)
LogErrorWithOptions executes a callback with the error message and structured fields, allowing for integration with any logging library.
If the error is not an Error, it logs the error message directly.
Example:
erro.LogErrorWithOptions(err, func(message string, fields ...any) {
myLogger.Error(message, fields...)
}, erro.LogOptions{
IncludeUserFields: true,
})
func LogFields ΒΆ
LogFields returns a slice of alternating key-value pairs for structured logging, extracted from the given error.
This is useful for integrating with logging libraries like `slog` that accept key-value pairs.
When option functions are provided, they are applied to a zero LogOptions value (not to DefaultLogOptions), so only the explicitly enabled parts are included and FieldNamePrefix is empty unless set with WithFieldNamePrefix. Field values are passed through as typed values without truncation β rendering is the logger's job.
Example:
slog.Error("something went wrong", erro.LogFields(err)...)
func LogFieldsMap ΒΆ
LogFieldsMap returns a map of field key-value pairs for structured logging, extracted from the given error.
This is useful for integrating with logging libraries like `logrus` that accept a map of fields.
Example:
logrus.WithFields(erro.LogFieldsMap(err)).Error("something went wrong")
func LogFieldsMapWithOptions ΒΆ
func LogFieldsMapWithOptions(err error, opts LogOptions) map[string]any
LogFieldsMapWithOptions returns a map of field key-value pairs for structured logging, extracted from the given error.
This is useful for integrating with logging libraries like `logrus` that accept a map of fields.
Example:
logrus.WithFields(erro.LogFieldsMapWithOptions(err, erro.LogOptions{
IncludeUserFields: true,
})).Error("something went wrong")
func LogFieldsWithOptions ΒΆ
func LogFieldsWithOptions(err error, opts LogOptions) []any
LogFieldsWithOptions returns a slice of alternating key-value pairs for structured logging, extracted from the given error.
This is useful for integrating with logging libraries like `slog` that accept key-value pairs.
Example:
slog.Error("something went wrong", erro.LogFieldsWithOptions(err, erro.LogOptions{
IncludeUserFields: true,
})...)
func RecordMetrics ΒΆ
func RecordMetrics(m ErrorMetrics) errorWork
RecordMetrics records the error with a metrics collector. A panic in the ErrorMetrics implementation propagates to the New/Wrap caller.
func RecordSpan ΒΆ
func RecordSpan(s TraceSpan) errorWork
RecordSpan records the error in a tracing span. Redacted field values are replaced with the placeholder before being passed to the span. A panic in the TraceSpan implementation propagates to the New/Wrap caller.
func SendEvent ΒΆ
func SendEvent(ctx context.Context, d EventDispatcher) errorWork
SendEvent sends the error to an event dispatcher. A panic in the EventDispatcher implementation propagates to the New/Wrap caller.
func Shutdown ΒΆ
func Shutdown(ctx context.Context, err *error, sd func(ctx context.Context) error, msg string, fields ...any)
Shutdown is a utility function that executes a shutdown function and wraps any resulting error. It is intended for use in cleanup operations.
If the shutdown function is nil, it does nothing. If the shutdown function returns an error, it will be wrapped with the provided message and fields.
Example:
func (s *Server) Stop(ctx context.Context) (err error) {
defer erro.Shutdown(ctx, &err, s.grpcServer.GracefulStop, "failed to stop gRPC server")
// ... other shutdown logic
}
func StackTrace ΒΆ
func StackTrace(c ...*StackTraceConfig) errorOpt
StackTrace captures a stack trace for the error.
func StackTraceWithSkip ΒΆ
func StackTraceWithSkip(skip int, c ...*StackTraceConfig) errorOpt
StackTraceWithSkip captures a stack trace, skipping a specified number of caller frames (erro's own construction frames are always excluded).
Types ΒΆ
type Error ΒΆ
type Error interface {
// error interface
error
fmt.Formatter
json.Marshaler
json.Unmarshaler
Is(target error) bool
As(target any) bool
Unwrap() error
// Metadata
ID() string
Class() ErrorClass
Category() ErrorCategory
Severity() ErrorSeverity
IsRetryable() bool
Message() string
Fields() []any
Span() TraceSpan
Created() time.Time
LogFields(opts ...LogOptions) []any
LogFieldsMap(opts ...LogOptions) map[string]any
// Wrapping
BaseError() Error
AllFields() []any
// Stack trace
Stack() Stack
}
Error represents the common interface for all erro errors.
func ExtractError ΒΆ
ExtractError ensures that an error can be treated as an Error.
If the given error is already an Error, it is returned as is. If the error merely contains an Error somewhere in its chain, that inner error is returned (outer non-erro layers are not represented in the result). If it's a standard error, it's wrapped in a new Error so that it can be used with the features of this package. If the error is nil, it returns nil.
func New ΒΆ
New creates a new Error with a message and optional structured metadata.
This is the primary function for creating rich, structured errors with comprehensive context and metadata. The returned error implements the standard error interface while providing extensive additional functionality for structured logging, error classification, stack traces, tracing integration, and more.
Basic Usage ΒΆ
err := erro.New("user not found")
err := erro.New("connection failed", "host", "localhost", "port", 5432)
Error Classification ΒΆ
Classify errors using predefined classes, categories, and severity levels:
err := erro.New("invalid email format",
erro.ClassValidation, // Error class for HTTP status mapping
erro.CategoryUserInput, // Error category for organization
erro.SeverityLow, // Severity level for prioritization
)
Structured Logging ΒΆ
Add context through key-value fields that integrate seamlessly with structured loggers:
err := erro.New("database query failed",
"table", "users",
"operation", "SELECT",
"duration_ms", 1500,
"rows_affected", 0,
)
// Use with slog
slog.Error("Operation failed", erro.LogFields(err)...)
// Use with logrus
logrus.WithFields(erro.LogFieldsMap(err)).Error("Operation failed")
Advanced Configuration ΒΆ
Use functional options for advanced error configuration:
err := erro.New("payment processing failed",
"amount", 29.99,
"currency", "USD",
"merchant_id", "merchant_123",
erro.ID("payment_error_001"), // Custom error ID for tracking
erro.Retryable(), // Mark as retryable for retry logic
erro.StackTrace(), // Capture stack trace for debugging
erro.ClassExternal, // External service error
erro.CategoryPayment, // Payment-related error
erro.SeverityCritical, // Critical severity level
erro.RecordSpan(span), // Record in tracing span
erro.RecordMetrics(metricsCollector), // Send to metrics system
erro.SendEvent(ctx, eventDispatcher), // Dispatch error event
erro.Formatter(customFormatter), // Custom error message formatting
)
JSON Serialization ΒΆ
Errors can be serialized for API responses or database storage:
jsonData, _ := json.Marshal(err) // Contains: id, class, category, severity, message, fields, stack_trace, etc.
Format Verb Support ΒΆ
The message supports format verbs when additional arguments are provided:
err := erro.New("user %s not found in database %s", "john_doe", "users_db",
"query_time_ms", 150,
erro.ClassNotFound,
)
// Message becomes: "user john_doe not found in database users_db"
Some Notes ΒΆ
- Stack traces are captured only when explicitly requested with StackTrace or StackTraceWithSkip - Field values are truncated to prevent memory exhaustion - Error IDs are automatically generated for tracking without performance impact - Structured fields are validated and limited to prevent DoS attacks
Thread Safety ΒΆ
Individual errors are immutable after creation and safe for concurrent use. For collecting multiple errors concurrently, use NewSafeList or NewSafeSet.
func Wrap ΒΆ
Wrap wraps an existing error with additional context, message, and optional metadata.
This function preserves the original error while adding a new layer of context, making it essential for error propagation across application layers. The wrapped error maintains full access to all original metadata while allowing additional context to be attached at each layer.
If the error to be wrapped is nil, Wrap returns nil, making it safe to use in conditional error handling patterns without explicit nil checks.
The wrap depth is limited to MaxWrapDepth: once a chain reaches that many erro layers, Wrap returns the existing error unchanged instead of adding another layer, keeping traversal costs bounded.
Basic Usage ΒΆ
if err != nil {
return erro.Wrap(err, "failed to process user request")
}
// With additional context
if err != nil {
return erro.Wrap(err, "database query failed",
"table", "users",
"operation", "UPDATE",
)
}
Advanced Wrapping Features ΒΆ
Enhance wrapped errors with comprehensive metadata and integrations:
err := erro.Wrap(dbErr, "user authentication failed",
"username", username,
"login_attempt", attemptCount,
"ip_address", clientIP,
"user_agent", erro.Redact(userAgent), // Redact potentially sensitive data
erro.ClassUnauthenticated, // Authentication failure
erro.CategoryAuth, // Authentication category
erro.SeverityMedium, // Medium severity
erro.ID("auth_failure_001"), // Custom error ID for tracking
erro.StackTrace(), // Capture new stack trace at wrap point
erro.RecordSpan(span), // Record in distributed tracing
erro.RecordMetrics(authMetrics), // Send to authentication metrics
erro.SendEvent(ctx, securityEvents), // Dispatch to security monitoring
)
Format Verb Support ΒΆ
Use format verbs in wrap messages for dynamic context:
err := erro.Wrap(originalErr, "failed to process %s for user %d",
operation, userID,
"retry_count", retryCount,
"processing_time_ms", duration.Milliseconds(),
)
Error Chain Inspection ΒΆ
Access the complete error chain and metadata:
wrappedErr := erro.Wrap(originalErr, "service layer failure")
// Access original error
originalErr := errors.Unwrap(wrappedErr)
// Check error types in chain
if errors.Is(wrappedErr, sql.ErrNoRows) {
// Handle specific database error
}
// Access all accumulated fields from error chain
allFields := wrappedErr.AllFields()
// Get inherited metadata from original error
errorClass := wrappedErr.Class() // Inherits from original if not overridden
errorCategory := wrappedErr.Category() // Inherits from original if not overridden
errorID := wrappedErr.ID() // Inherits from original error
Performance and Memory Considerations ΒΆ
- Error wrapping is lightweight and optimized for high-frequency use
- Original error references are preserved efficiently without deep copying
- Field values are automatically truncated to prevent memory exhaustion
- Stack traces are captured only when explicitly requested with StackTrace or StackTraceWithSkip
Thread Safety ΒΆ
Wrapped errors are immutable and safe for concurrent access across goroutines. The wrapping operation itself is thread-safe and can be called concurrently.
type ErrorCategory ΒΆ
type ErrorCategory string
ErrorCategory represents the category of an error.
const ( // CategoryDatabase indicates a database-related error. CategoryDatabase ErrorCategory = "database" // CategoryNetwork indicates a network-related error. CategoryNetwork ErrorCategory = "network" // CategoryOS indicates an operating system-related error. CategoryOS ErrorCategory = "os" // CategoryAuth indicates an authentication or authorization error. CategoryAuth ErrorCategory = "auth" // CategorySecurity indicates a security-related error. CategorySecurity ErrorCategory = "security" // CategoryPayment indicates a payment-related error. CategoryPayment ErrorCategory = "payment" // CategoryAPI indicates an API-related error. CategoryAPI ErrorCategory = "api" // CategoryBusinessLogic indicates an error in business logic. CategoryBusinessLogic ErrorCategory = "business_logic" // CategoryCache indicates a cache-related error. CategoryCache ErrorCategory = "cache" // CategoryConfig indicates a configuration error. CategoryConfig ErrorCategory = "config" // CategoryExternal indicates an error from an external service. CategoryExternal ErrorCategory = "external" // CategoryUserInput indicates an error due to invalid user input. CategoryUserInput ErrorCategory = "user_input" // CategoryEvents indicates an event-related error. CategoryEvents ErrorCategory = "events" // CategoryMonitoring indicates a monitoring-related error. CategoryMonitoring ErrorCategory = "monitoring" // CategoryNotifications indicates a notification-related error. CategoryNotifications ErrorCategory = "notifications" // CategoryStorage indicates a storage-related error. CategoryStorage ErrorCategory = "storage" // CategoryProcessing indicates a data processing error. CategoryProcessing ErrorCategory = "processing" // CategoryAnalytics indicates an analytics-related error. CategoryAnalytics ErrorCategory = "analytics" // CategoryAI indicates an AI/ML-related error. CategoryAI ErrorCategory = "ai" // CategoryUnknown represents an unknown error category. CategoryUnknown ErrorCategory = "" )
func (ErrorCategory) String ΒΆ
func (c ErrorCategory) String() string
String returns the string representation of ErrorCategory.
type ErrorClass ΒΆ
type ErrorClass string
ErrorClass represents the class of an error.
const ( // ClassValidation indicates an error due to invalid input. ClassValidation ErrorClass = "validation" // ClassNotFound indicates that a resource was not found. ClassNotFound ErrorClass = "not_found" // ClassAlreadyExists indicates that a resource already exists. ClassAlreadyExists ErrorClass = "already_exists" // ClassPermissionDenied indicates a permission error. ClassPermissionDenied ErrorClass = "permission_denied" // ClassUnauthenticated indicates an authentication error. ClassUnauthenticated ErrorClass = "unauthenticated" // ClassTimeout indicates that an operation timed out. ClassTimeout ErrorClass = "timeout" // ClassConflict indicates a conflict with the current state of a resource. ClassConflict ErrorClass = "conflict" // ClassRateLimited indicates that a rate limit has been exceeded. ClassRateLimited ErrorClass = "rate_limited" // ClassTemporary indicates a temporary error that may be resolved on retry. ClassTemporary ErrorClass = "temporary" ClassUnavailable ErrorClass = "unavailable" // ClassInternal indicates a generic internal error. ClassInternal ErrorClass = "internal" // ClassCancelled indicates that an operation was cancelled. ClassCancelled ErrorClass = "cancelled" // ClassNotImplemented indicates that a feature is not implemented. ClassNotImplemented ErrorClass = "not_implemented" // ClassSecurity indicates a security-related error. ClassSecurity ErrorClass = "security" // ClassCritical indicates a critical, unrecoverable error. ClassCritical ErrorClass = "critical" // ClassExternal indicates an error from an external service. ClassExternal ErrorClass = "external" // ClassDataLoss indicates a loss of data. ClassDataLoss ErrorClass = "data_loss" // ClassResourceExhausted indicates that a resource has been exhausted. ClassResourceExhausted ErrorClass = "resource_exhausted" // ClassUnknown represents an unknown error class. ClassUnknown ErrorClass = "" )
func (ErrorClass) String ΒΆ
func (c ErrorClass) String() string
String returns the string representation of ErrorClass.
type ErrorMetrics ΒΆ
type ErrorMetrics interface {
RecordError(err Error)
}
ErrorMetrics is an interface for recording error metrics.
type ErrorSchema ΒΆ
type ErrorSchema struct {
ID string `json:"id" bson:"_id" db:"id"`
Class ErrorClass `json:"class,omitempty" bson:"class,omitempty" db:"class,omitempty"`
Category ErrorCategory `json:"category,omitempty" bson:"category,omitempty" db:"category,omitempty"`
Severity ErrorSeverity `json:"severity,omitempty" bson:"severity,omitempty" db:"severity,omitempty"`
Created time.Time `json:"created,omitempty" bson:"created,omitempty" db:"created,omitempty"`
Message string `json:"message,omitempty" bson:"message,omitempty" db:"message,omitempty"`
Fields []any `json:"fields,omitempty" bson:"fields,omitempty" db:"fields,omitempty"`
Retryable bool `json:"retryable,omitempty" bson:"retryable,omitempty" db:"retryable,omitempty"`
StackTrace []StackContext `json:"stack_trace,omitempty" bson:"stack_trace,omitempty" db:"stack_trace,omitempty"`
TraceID string `json:"trace_id,omitempty" bson:"trace_id,omitempty" db:"trace_id,omitempty"`
SpanID string `json:"span_id,omitempty" bson:"span_id,omitempty" db:"span_id,omitempty"`
ParentSpanID string `json:"parent_span_id,omitempty" bson:"parent_span_id,omitempty" db:"parent_span_id,omitempty"`
}
ErrorSchema is a serializable representation of an error.
func ErrorToJSON ΒΆ
func ErrorToJSON(err Error) ErrorSchema
ErrorToJSON converts an error to a serializable ErrorSchema struct.
This is useful for sending error details over the network or storing them in a structured format. Sensitive fields are redacted.
type ErrorSeverity ΒΆ
type ErrorSeverity string
ErrorSeverity represents the severity level of an error.
const ( SeverityCritical ErrorSeverity = "critical" SeverityHigh ErrorSeverity = "high" SeverityMedium ErrorSeverity = "medium" SeverityLow ErrorSeverity = "low" SeverityInfo ErrorSeverity = "info" SeverityUnknown ErrorSeverity = "" )
Predefined error severity levels.
func (ErrorSeverity) IsCritical ΒΆ
func (s ErrorSeverity) IsCritical() bool
IsCritical returns true if the severity is Critical.
func (ErrorSeverity) IsHigh ΒΆ
func (s ErrorSeverity) IsHigh() bool
IsHigh returns true if the severity is High.
func (ErrorSeverity) IsInfo ΒΆ
func (s ErrorSeverity) IsInfo() bool
IsInfo returns true if the severity is Info.
func (ErrorSeverity) IsLow ΒΆ
func (s ErrorSeverity) IsLow() bool
IsLow returns true if the severity is Low.
func (ErrorSeverity) IsMedium ΒΆ
func (s ErrorSeverity) IsMedium() bool
IsMedium returns true if the severity is Medium.
func (ErrorSeverity) IsUnknown ΒΆ
func (s ErrorSeverity) IsUnknown() bool
IsUnknown returns true if the severity is Unknown.
func (ErrorSeverity) IsValid ΒΆ
func (s ErrorSeverity) IsValid() bool
IsValid checks if the severity is one of the predefined values.
func (ErrorSeverity) Label ΒΆ
func (s ErrorSeverity) Label() string
Label returns a short, human-readable label for the severity level.
func (ErrorSeverity) String ΒΆ
func (s ErrorSeverity) String() string
String returns the string representation of ErrorSeverity.
type ErrorTemplate ΒΆ
type ErrorTemplate struct {
// contains filtered or unexported fields
}
ErrorTemplate represents a template for creating errors with predefined metadata.
func NewTemplate ΒΆ
func NewTemplate(messageTemplate string, opts ...any) *ErrorTemplate
NewTemplate creates a new error template with a message and predefined options.
func (*ErrorTemplate) New ΒΆ
func (t *ErrorTemplate) New(fields ...any) Error
New creates an error from the template.
type EventDispatcher ΒΆ
EventDispatcher is an interface for sending error events.
type FormatErrorFunc ΒΆ
FormatErrorFunc is a function that formats an error into a string.
func GetFormatErrorWithFullContext ΒΆ
func GetFormatErrorWithFullContext(optFuncs ...LogOption) FormatErrorFunc
GetFormatErrorWithFullContext returns a FormatErrorFunc that formats an error with full context, including log fields.
func GetFormatErrorWithFullContextBase ΒΆ
func GetFormatErrorWithFullContextBase(optFuncs ...LogOption) FormatErrorFunc
GetFormatErrorWithFullContextBase returns a FormatErrorFunc that formats an error with full context.
type KeyGetterFunc ΒΆ
KeyGetterFunc is a function that generates a key for an error, used for deduplication.
var ( // MessageKeyGetter generates a key based on the error's message without fields. MessageKeyGetter KeyGetterFunc = func(err error) string { if err == nil { return "" } if erroErr, ok := err.(Error); ok { return erroErr.Message() } var erroErr Error if As(err, &erroErr) { return erroErr.Message() } return err.Error() } // IDKeyGetter generates a key based on the error's ID. IDKeyGetter KeyGetterFunc = func(err error) string { if err == nil { return "" } if erroErr, ok := err.(Error); ok { return erroErr.ID() } var erroErr Error if As(err, &erroErr) { return erroErr.ID() } return err.Error() } // ErrorKeyGetter generates a key based on the error's string representation (err.Error()). ErrorKeyGetter KeyGetterFunc = func(err error) string { if err == nil { return "" } return err.Error() } )
Key getter functions for deduplication
type List ΒΆ
type List struct {
// contains filtered or unexported fields
}
List collects multiple errors and provides a fluent API for adding and configuring them. It is not thread-safe. For a thread-safe version, see SafeList.
func (*List) Add ΒΆ
Add adds an error to the list. If the error is not already an Error, it is converted to one. If the error is nil, it is ignored.
func (*List) Err ΒΆ
Err returns a single error representing all errors in the list. If the list is empty, it returns nil. If the list contains a single error, that error is returned. If the list contains multiple errors, they are combined into a multi-error.
func (*List) Errors ΒΆ
Errors returns a slice of all errors in the list as standard `error` interfaces.
func (*List) Errs ΒΆ
Errs returns a slice of all errors in the list as Error interfaces. The returned slice is a copy and can be safely retained by the caller.
func (*List) New ΒΆ
New creates a new error with the given message and metadata, and adds it to the list.
func (*List) Remove ΒΆ
Remove removes an error at the specified index from the list. It returns true if the removal was successful, and false otherwise.
func (*List) RemoveError ΒΆ
RemoveError removes the first error that matches the given error by ID. It returns true if an error was removed, and false otherwise.
type LogOption ΒΆ
type LogOption func(*LogOptions)
LogOption is a function that configures logging options.
func MergeLogOpts ΒΆ
MergeLogOpts merges multiple slices of LogOption functions into one.
func WithCategory ΒΆ
WithCategory returns a LogOption to enable or disable the error category field.
func WithCreatedTime ΒΆ
WithCreatedTime returns a LogOption to enable or disable the creation timestamp field.
func WithErrorMessage ΒΆ added in v1.0.1
WithErrorMessage returns a LogOption to enable or disable the error message field.
func WithFieldNamePrefix ΒΆ
WithFieldNamePrefix returns a LogOption to set the field name prefix.
func WithFunction ΒΆ
WithFunction returns a LogOption to enable or disable the function name field.
func WithPackage ΒΆ
WithPackage returns a LogOption to enable or disable the package name field.
func WithRetryable ΒΆ
WithRetryable returns a LogOption to enable or disable the retryable flag field.
func WithSeverity ΒΆ
WithSeverity returns a LogOption to enable or disable the error severity field.
func WithStackFormat ΒΆ
func WithStackFormat(format StackFormat) LogOption
WithStackFormat returns a LogOption to set the stack trace format.
func WithTracing ΒΆ
WithTracing returns a LogOption to enable or disable tracing fields.
func WithUserFields ΒΆ
WithUserFields returns a LogOption to enable or disable user-defined fields.
type LogOptions ΒΆ
type LogOptions struct {
// IncludeErrorMessage determines whether to include the error message.
IncludeErrorMessage bool
// IncludeUserFields determines whether to include user-defined fields.
IncludeUserFields bool
// IncludeID determines whether to include the error ID.
IncludeID bool
// IncludeCategory determines whether to include the error category.
IncludeCategory bool
// IncludeSeverity determines whether to include the error severity.
IncludeSeverity bool
// IncludeRetryable determines whether to include the retryable flag.
IncludeRetryable bool
// IncludeTracing determines whether to include tracing information (TraceID, SpanID).
IncludeTracing bool
// IncludeCreatedTime determines whether to include the error creation timestamp.
IncludeCreatedTime bool
// IncludeFunction determines whether to include the function name from the stack trace.
IncludeFunction bool
// IncludePackage determines whether to include the package name from the stack trace.
IncludePackage bool
// IncludeFile determines whether to include the file name from the stack trace.
IncludeFile bool
// IncludeLine determines whether to include the line number from the stack trace.
IncludeLine bool
// IncludeStack determines whether to include the full stack trace.
IncludeStack bool
// StackFormat defines how stack traces should be formatted.
StackFormat StackFormat
// FieldNamePrefix is a prefix added to all field names. Default is "error_".
FieldNamePrefix string
}
LogOptions controls which fields are included in logging output.
func (*LogOptions) ApplyOptions ΒΆ
func (opts *LogOptions) ApplyOptions(optFuncs ...LogOption) LogOptions
ApplyOptions applies a set of option functions to LogOptions.
type RedactedValue ΒΆ
type RedactedValue struct {
Value any
}
RedactedValue is a wrapper for a value that should be redacted in logs.
func Redact ΒΆ
func Redact(value any) RedactedValue
Redact wraps a value to mark it as sensitive. Its content will be replaced with RedactedPlaceholder when the error is formatted as a string or JSON.
func (RedactedValue) GoString ΒΆ added in v1.0.3
func (r RedactedValue) GoString() string
GoString implements fmt.GoStringer so the wrapped value is never revealed through the %#v verb.
func (RedactedValue) MarshalJSON ΒΆ added in v1.0.3
func (r RedactedValue) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler so the wrapped value is never revealed when marshaled to JSON.
func (RedactedValue) String ΒΆ added in v1.0.3
func (r RedactedValue) String() string
String implements fmt.Stringer so the wrapped value is never revealed through fmt verbs like %v and %s.
type SafeList ΒΆ
type SafeList struct {
// contains filtered or unexported fields
}
SafeList is a thread-safe version of List.
func NewSafeList ΒΆ
NewSafeList creates a new thread-safe error list.
func (*SafeList) Empty ΒΆ
Empty returns true if the list contains no errors in a thread-safe manner.
func (*SafeList) Err ΒΆ
Err returns a combined error from all errors in the list in a thread-safe manner.
func (*SafeList) Errors ΒΆ
Errors returns a slice of all errors in the list as standard `error` interfaces in a thread-safe manner.
func (*SafeList) Errs ΒΆ
Errs returns a slice of all errors in the list as `erro.Error` interfaces in a thread-safe manner.
func (*SafeList) NotEmpty ΒΆ
NotEmpty returns true if the list contains at least one error in a thread-safe manner.
func (*SafeList) RemoveError ΒΆ
RemoveError removes the first error that matches the given error by ID in a thread-safe manner.
type SafeSet ΒΆ
type SafeSet struct {
// contains filtered or unexported fields
}
SafeSet is a thread-safe version of Set.
func NewSafeSet ΒΆ
NewSafeSet creates a new thread-safe error set.
func (*SafeSet) Err ΒΆ
Err returns a combined error from all errors in the set in a thread-safe manner.
func (*SafeSet) Errors ΒΆ
Errors returns a slice of all errors in the set as standard `error` interfaces in a thread-safe manner.
func (*SafeSet) Errs ΒΆ
Errs returns a slice of all errors in the set as `erro.Error` interfaces in a thread-safe manner.
func (*SafeSet) NotEmpty ΒΆ
NotEmpty returns true if the set contains at least one error in a thread-safe manner.
func (*SafeSet) RemoveError ΒΆ
RemoveError removes the first error that matches the given error by ID in a thread-safe manner.
func (*SafeSet) WithKeyGetter ΒΆ
func (ss *SafeSet) WithKeyGetter(keyGetter KeyGetterFunc) *SafeSet
WithKeyGetter sets the function used to generate deduplication keys for errors in a thread-safe manner.
type Set ΒΆ
type Set struct {
*List
// contains filtered or unexported fields
}
Set collects unique errors, deduplicating them based on a configurable key. It is not thread-safe. For a thread-safe version, see SafeSet.
Note: Set embeds List for its accessors. Calling mutating methods directly on the embedded List (e.g. set.List.Add) bypasses deduplication and desyncs the internal counters β always use the Set's own methods.
func NewSet ΒΆ
NewSet creates a new error set that stores only unique errors, with an optional initial capacity.
func (*Set) Add ΒΆ
Add adds an error to the set. If the error is not already an Error, it is converted to one. If the error is nil, it is ignored.
func (*Set) Err ΒΆ
Err returns a combined error that includes deduplication counts. If the set is empty, it returns nil. If the set contains a single error, that error is returned. If the set contains multiple errors, they are combined into a multi-error.
func (*Set) Remove ΒΆ
Remove removes an error and its key from the seen map. It returns true if an error was removed, and false otherwise.
func (*Set) RemoveError ΒΆ
RemoveError removes an error by its instance and its key from the seen map. It returns true if an error was removed, and false otherwise.
func (*Set) WithKeyGetter ΒΆ
func (s *Set) WithKeyGetter(keyGetter KeyGetterFunc) *Set
WithKeyGetter sets the function used to generate deduplication keys for errors.
type Stack ΒΆ
type Stack []StackFrame
Stack represents a collection of stack frames with enhanced analysis capabilities.
func (Stack) ContainsFunction ΒΆ
ContainsFunction returns true if the stack contains a frame with the given function name.
func (Stack) ExtractPackages ΒΆ
ExtractPackages returns unique packages involved in the error.
func (Stack) FilterByPackage ΒΆ
FilterByPackage returns frames that belong to the specified package.
func (Stack) FormatFull ΒΆ
FormatFull returns a detailed formatted stack trace.
func (Stack) GetCallChain ΒΆ
GetCallChain returns the call chain of user functions leading to the error.
func (Stack) GetOriginContext ΒΆ
func (s Stack) GetOriginContext() *StackContext
GetOriginContext returns context information about where the error originated.
func (Stack) IsGlobalError ΒΆ
IsGlobalError determines if the stack trace represents a global/init error.
func (Stack) ToJSONUserFrames ΒΆ
ToJSONUserFrames returns a JSON-friendly representation of user frames only.
func (Stack) ToLogFields ΒΆ
ToLogFields converts stack context to logging fields.
func (Stack) TopUserFrame ΒΆ
func (s Stack) TopUserFrame() *StackFrame
TopUserFrame returns the topmost user code frame (where the error likely originated).
func (Stack) UserFrames ΒΆ
UserFrames returns only the user code frames, filtering out runtime and stdlib.
type StackContext ΒΆ
type StackContext struct {
Function string `json:"function" bson:"function" db:"function"`
Package string `json:"package" bson:"package" db:"package"`
Module string `json:"module" bson:"module" db:"module"`
File string `json:"file" bson:"file" db:"file"`
Line int `json:"line" bson:"line" db:"line"`
IsUserCode bool `json:"is_user_code" bson:"is_user_code" db:"is_user_code"`
Metadata map[string]string `json:"metadata" bson:"metadata" db:"metadata"`
}
StackContext extracts contextual information from the stack frame.
type StackFormat ΒΆ
type StackFormat int
StackFormat defines how stack traces should be formatted in logs.
const ( // StackFormatString formats the stack trace as a single string. StackFormatString StackFormat = iota // StackFormatList formats the stack trace as a list of function calls. StackFormatList // StackFormatFull formats the stack trace with detailed information. StackFormatFull // StackFormatJSON formats the stack trace as a JSON object. StackFormatJSON )
type StackFrame ΒΆ
type StackFrame struct {
Name string // Function name (e.g., "processPayment")
FullName string // Full function name (e.g., "github.com/app/payment.processPayment")
Package string // Package name (e.g., "payment")
File string // Full file path
FileName string // Just the filename (e.g., "payment.go")
Line int // Line number
StackTraceConfig *StackTraceConfig
}
StackFrame stores a frame's runtime information in a human-readable format, enhanced with additional context for better error diagnostics.
func (StackFrame) FormatFull ΒΆ
func (f StackFrame) FormatFull() string
FormatFull returns a detailed formatted stack frame.
func (StackFrame) GetContext ΒΆ
func (f StackFrame) GetContext() StackContext
GetContext extracts rich context information from the stack frame.
func (StackFrame) IsErroInternal ΒΆ
func (f StackFrame) IsErroInternal() bool
IsErroInternal returns true if this frame is from erro internal functions.
func (StackFrame) IsRuntime ΒΆ
func (f StackFrame) IsRuntime() bool
IsRuntime returns true if this frame is from the Go runtime.
func (StackFrame) IsStandardLibrary ΒΆ
func (f StackFrame) IsStandardLibrary() bool
IsStandardLibrary returns true if this frame is from the Go standard library.
func (StackFrame) IsTest ΒΆ
func (f StackFrame) IsTest() bool
IsTest returns true if this frame is from test code.
func (StackFrame) IsUser ΒΆ
func (f StackFrame) IsUser() bool
IsUser returns true if this frame represents user code (not runtime, stdlib, or erro internal).
func (StackFrame) String ΒΆ
func (f StackFrame) String() string
String returns a formatted representation of the stack frame.
func (StackFrame) ToJSON ΒΆ
func (f StackFrame) ToJSON() map[string]any
ToJSON returns a JSON-friendly representation of the stack frame.
type StackTraceConfig ΒΆ
type StackTraceConfig struct {
ShowFileNames bool // Whether to show file names.
ShowFullPaths bool // Whether to show full file paths.
PathElements int // Number of path elements to include (0 = filename only, -1 = full path).
ShowFunctionNames bool // Whether to show function names.
ShowPackageNames bool // Whether to show package names.
ShowLineNumbers bool // Whether to show line numbers.
ShowAllCodeFrames bool // Whether to show all types of frames (user, stdlib, etc.).
FunctionRedacted string // Placeholder for redacted function names.
FileNameRedacted string // Placeholder for redacted file names.
MaxFrames int // Maximum number of frames to show.
}
StackTraceConfig controls what information is included in stack traces.
func DevelopmentStackTraceConfig ΒΆ
func DevelopmentStackTraceConfig() *StackTraceConfig
DevelopmentStackTraceConfig returns a stack trace configuration suitable for development environments.
func ProductionStackTraceConfig ΒΆ
func ProductionStackTraceConfig() *StackTraceConfig
ProductionStackTraceConfig returns a stack trace configuration suitable for production environments.
func StrictStackTraceConfig ΒΆ
func StrictStackTraceConfig() *StackTraceConfig
StrictStackTraceConfig returns a strict privacy stack trace configuration.