Documentation
¶
Overview ¶
Package errors provides a structured and extensible way to create, wrap, and manage errors in Go applications. It includes support for adding contextual information, managing error hierarchies, and setting attributes such as severity, HTTP status codes, and custom error codes.
The package is designed to enhance error handling by allowing developers to attach additional metadata to errors, wrap underlying errors with more context, and facilitate debugging and logging. It also supports integration with alerting systems through the Alarm method.
Key features include: - Wrapping errors with additional context. - Setting custom attributes like severity, status codes, and business codes. - Managing error stacks and hierarchies. - Sending alerts for critical errors. - Support for custom key-value pairs to enrich error information. - Integration with predefined error types for common scenarios. - Serialization errors for easy logging.
Index ¶
- Constants
- Variables
- func As(err error, target any) bool
- func Is(err error, target error) bool
- func New(msg string) error
- func SetAlarmer(a Alarmer)
- func ToJSON(err error, opts ...Option) []byte
- type Alarmer
- type Error
- func (e *Error) Alarm()
- func (e *Error) Code(code string) *Error
- func (e *Error) Error() string
- func (e *Error) Msg(s string) *Error
- func (e *Error) Protected(protected bool) *Error
- func (e *Error) Set(key string, value any) *Error
- func (e *Error) Severity(severity SeverityLevel) *Error
- func (e *Error) StatusCode(statusCode int) *Error
- func (e *Error) Wrap(err error) *Error
- func (err *Error) WrappedErrors() []Error
- type ErrorFormattingOptions
- type ErrorSerializationRule
- type ErrorTemplate
- func (et *ErrorTemplate) Code(code string) *ErrorTemplate
- func (et *ErrorTemplate) Error() string
- func (et *ErrorTemplate) New() *Error
- func (et *ErrorTemplate) Protected(protected bool) *ErrorTemplate
- func (et *ErrorTemplate) Set(key string, value any) *ErrorTemplate
- func (et *ErrorTemplate) Severity(severity SeverityLevel) *ErrorTemplate
- func (et *ErrorTemplate) StatusCode(statusCode int) *ErrorTemplate
- func (et *ErrorTemplate) Wrap(err error) *Error
- type Option
- type SerializedError
- type SeverityLevel
- type StackFrame
Examples ¶
Constants ¶
const ( ServerOutputFormat = AddProtected | AddStack | AddFields | AddWrappedErrors ServerDebugOutputFormat = AddProtected | AddStack | AddFields | AddWrappedErrors | IndentJSON ClientDebugOutputFormat = AddProtected | AddStack | AddFields | AddWrappedErrors ClientOutputFormat = 0 // no fields, no stack, no wrapped errors, only message. )
Variables ¶
var ( // CallerFramesFunc holds default function used by function Catch() // to collect call frames. CallerFramesFunc func(offset int) []StackFrame = DefaultCallerFrames // CallingStackMaxLen holds maximum elements in the call frames. CallingStackMaxLen int = 15 )
var ErrMarshalError = Template("error marshaling failed").Severity(Critical).StatusCode(500)
Functions ¶
func New ¶
New creates and returns a standard Go error using the built-in errors.New function.
This is implemented to maintain compatibility with existing Go error handling practices. However, the design philosophy of this package does not encourage the use of errors.New(msg) as commonly practiced in Go. Instead, it promotes the use of structured and enriched error handling mechanisms provided by this package.
func SetAlarmer ¶ added in v1.0.0
func SetAlarmer(a Alarmer)
SetAlarmer sets Alarmer implementation to be used when critical error is caught.
func ToJSON ¶ added in v0.0.2
ToJSON serializes the error to JSON format.
Example ¶
ExampleToJSON demonstrates generating JSON output for an error.
package main import ( "fmt" "github.com/axkit/errors" ) func main() { jsonErr := errors.Template("User not found").Code("E404").StatusCode(404).Severity(errors.Tiny) jsonOutput := errors.ToJSON(jsonErr, errors.WithAttributes(errors.AddFields)) fmt.Println("JSON Error:", string(jsonOutput)) }
Output: JSON Error: {"msg":"User not found","severity":"tiny","code":"E404","statusCode":404}
Types ¶
type Alarmer ¶ added in v0.0.2
type Alarmer interface {
Alarm(err error)
}
Alarmer is an interface wrapping a single method Alarm
Alarm is invocated automatically when critical error is caught, if alarmer is set.
Example ¶
package main import ( "fmt" "github.com/axkit/errors" ) type CustomAlarmer struct{} func (c *CustomAlarmer) Alarm(err error) { fmt.Println("Critical error:", err) } func main() { errors.SetAlarmer(&CustomAlarmer{}) var ErrSystemFailure = errors.Template("system failure").Severity(errors.Critical) ErrSystemFailure.New().Set("path", "/var/lib").Alarm() }
Output: Critical error: system failure
type Error ¶ added in v1.0.0
type Error struct {
// contains filtered or unexported fields
}
Error represents a structured error with metadata, custom fields, stack trace, and optional wrapping.
func Wrap ¶ added in v0.0.6
Wrap wraps an existing error with a new message, effectively creating a new error that includes the previous error.
Example ¶
ExampleWrap demonstrates wrapping an error.
package main import ( "fmt" "github.com/axkit/errors" ) func main() { innerErr := errors.Template("Database connection failed") outerErr := errors.Template("Service initialization failed").Wrap(innerErr) fmt.Println("Wrapped Error:", outerErr.Error()) }
Output: Wrapped Error: Service initialization failed: Database connection failed
func (*Error) Alarm ¶ added in v1.0.0
func (e *Error) Alarm()
Alarm triggers an alert for the error if an alarmer is configured.
func (*Error) Error ¶ added in v1.0.0
Error returns the error message, including any wrapped error messages.
Example ¶
package main import ( "fmt" "github.com/axkit/errors" ) func main() { type Input struct { ID int `json:"id"` FirstName string `json:"firstName"` LastName string `json:"lastName"` } var ErrEmptyAttribute = errors.Template("empty attribute value").Code("CMN-0400") var ErrInvalidInput = errors.Template("invalid input").Code("CMN-0400") validateInput := func(inp *Input) error { if inp.ID == 0 { return ErrEmptyAttribute.New().Set("emptyFields", []string{"id"}) } return nil } if err := validateInput(&Input{}); err != nil { returnErr := ErrInvalidInput.Wrap(err) fmt.Println(returnErr.Error()) } }
Output: invalid input: empty attribute value
func (*Error) Msg ¶ added in v1.0.0
Msg sets the error message and marks the error as not being a pure wrapper.
func (*Error) Protected ¶ added in v1.0.0
Protected marks the error as protected to prevent certain modifications or exposure.
func (*Error) Set ¶ added in v1.0.0
Set adds or updates a custom key-value pair in the error's fields.
func (*Error) Severity ¶ added in v1.0.0
func (e *Error) Severity(severity SeverityLevel) *Error
Severity sets the severity level for the error.
func (*Error) StatusCode ¶ added in v1.0.0
StatusCode sets the associated HTTP status code for the error.
func (*Error) Wrap ¶ added in v1.0.0
Wrap returns a new Error that wraps the given error while retaining the current error's metadata and fields. It also preserves the stack trace of the wrapped error if available. The new error is marked as a pure wrapper if the original error is of type ErrorTemplate or Error. If the original error is nil, it returns the current error. This method is useful for chaining errors and maintaining context. It supports wrapping both ErrorTemplate and Error types, preserving their fields and stack trace.
func (*Error) WrappedErrors ¶ added in v1.0.0
WrappedErrors returns a slice of all wrapped errors, including the current one if it's not a pure wrapper.
type ErrorFormattingOptions ¶ added in v1.0.0
type ErrorFormattingOptions struct {
// contains filtered or unexported fields
}
type ErrorSerializationRule ¶ added in v1.0.0
type ErrorSerializationRule uint8
const ( // AddStack - add stack in the JSON. AddStack ErrorSerializationRule = 1 << iota // AddProtected - add protected errors in the JSON. AddProtected // AddFields - add fields in the JSON. AddFields // AddWrappedErrors - add previous errors in the JSON. AddWrappedErrors IndentJSON )
type ErrorTemplate ¶ added in v1.0.0
type ErrorTemplate struct {
// contains filtered or unexported fields
}
ErrorTemplate defines a reusable error blueprint that includes metadata and custom key-value fields. It is designed for creating structured errors with consistent attributes such as severity and HTTP status code.
Example ¶
ExamplePredefinedErrors demonstrates using predefined errors.
package main import ( "fmt" "github.com/axkit/errors" ) func main() { var ErrDatabaseDown = errors.Template("Database is unreachable"). Code("DB-500"). StatusCode(500). Severity(errors.Critical) if err := openDatabase("pg:5432"); err != nil { fmt.Println("Error:", ErrDatabaseDown.Wrap(err).Error()) } } func openDatabase(connStr string) error { var dbErr error return errors.Wrap(dbErr, "unable to connect to database").Set("connectionString", connStr) }
Output: Error: Database is unreachable: unable to connect to database
func Template ¶ added in v1.0.0
func Template(msg string) *ErrorTemplate
Template returns a new ErrorTemplate initialized with the given message. It can be extended with additional attributes and reused to create multiple error instances.
func (*ErrorTemplate) Code ¶ added in v1.0.0
func (et *ErrorTemplate) Code(code string) *ErrorTemplate
Code sets an application-specific error code on the template.
func (*ErrorTemplate) Error ¶ added in v1.0.0
func (et *ErrorTemplate) Error() string
Error returns the error message from the template.
func (*ErrorTemplate) New ¶ added in v1.0.0
func (et *ErrorTemplate) New() *Error
New creates a new Error instance using the template's metadata and fields. A new stack trace is captured at the point of the call.
func (*ErrorTemplate) Protected ¶ added in v1.0.0
func (et *ErrorTemplate) Protected(protected bool) *ErrorTemplate
Protected marks the error as protected, indicating it should not be exposed externally.
func (*ErrorTemplate) Set ¶ added in v1.0.0
func (et *ErrorTemplate) Set(key string, value any) *ErrorTemplate
Set adds a custom key-value pair to the template's fields.
func (*ErrorTemplate) Severity ¶ added in v1.0.0
func (et *ErrorTemplate) Severity(severity SeverityLevel) *ErrorTemplate
Severity sets the severity level for the error template.
func (*ErrorTemplate) StatusCode ¶ added in v1.0.0
func (et *ErrorTemplate) StatusCode(statusCode int) *ErrorTemplate
StatusCode sets the HTTP status code associated with the error.
func (*ErrorTemplate) Wrap ¶ added in v1.0.0
func (et *ErrorTemplate) Wrap(err error) *Error
Wrap wraps an existing error with the ErrorTemplate's metadata and fields. It supports wrapping both ErrorTemplate and Error types, preserving their fields and stack trace.
type Option ¶ added in v1.0.0
type Option func(*ErrorFormattingOptions)
func WithAttributes ¶ added in v1.0.0
func WithAttributes(rule ErrorSerializationRule) Option
func WithRootLevelFields ¶ added in v1.0.0
func WithStopStackOn ¶ added in v1.0.0
WithStopStackOn sets the function name to stop the adding stack frames. As instance: WithStopStackOn("fasthttp") will stop adding stack frames when the function name contains "fasthttp". It's useful to avoid adding stack frames of the libraries which are not interesting for the user.
type SerializedError ¶ added in v1.0.0
type SerializedError struct { Message string `json:"msg"` Severity string `json:"severity,omitempty"` Code string `json:"code,omitempty"` StatusCode int `json:"statusCode,omitempty"` Fields map[string]any `json:"fields,omitempty"` Wrapped []SerializedError `json:"wrapped,omitempty"` Stack []StackFrame `json:"stack,omitempty"` }
SerializedError is serialization ready error.
func Serialize ¶ added in v1.0.0
func Serialize(err error, opts ...Option) *SerializedError
Serialize serializes the error to a SerializedError struct.
type SeverityLevel ¶
type SeverityLevel int
SeverityLevel describes error severity levels.
const ( Unknown SeverityLevel = iota // Tiny classifies expected, managed errors that do not require administrator attention. // Writing a call stack to the journal file is not recommended. // // Example: error related to validation of entered form fields. Tiny // Medium classifies a regular error. A call stack is written to the log. Medium // Critical classifies a significant error, requiring immediate attention. // The occurrence of the error should be communicated to the administrator // through all available channels. A call stack is written to the log. // If Alarmer is set, it will be called. Critical )
func (SeverityLevel) MarshalJSON ¶
func (sl SeverityLevel) MarshalJSON() ([]byte, error)
MarshalJSON implements json/Marshaller interface.
func (SeverityLevel) String ¶
func (sl SeverityLevel) String() string
String returns severity level string representation.
func (*SeverityLevel) UnmarshalJSON ¶ added in v1.0.0
func (sl *SeverityLevel) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json/Unmarshaller interface.
type StackFrame ¶ added in v1.0.0
type StackFrame struct { Function string `json:"func"` File string `json:"file"` Line int `json:"line"` }
StackFrame describes content of a single stack frame stored with error.
func DefaultCallerFrames ¶ added in v0.0.2
func DefaultCallerFrames(offset int) []StackFrame
DefaultCallerFrames returns default implementation of call frames collector.
func (StackFrame) String ¶ added in v1.0.0
func (s StackFrame) String() string