Documentation
¶
Overview ¶
Package errors extends the standard errors package with stack traces, typed attachments, and enhanced error formatting capabilities.
Index ¶
- Variables
- func As(err error, target any) bool
- func Attachment[T any](err error) (v T, ok bool)
- func Errorf(format string, args ...interface{}) error
- func Ignore(error)
- func Is(err, target error) bool
- func Join(errs ...error) error
- func Must[T any](v T, err error) T
- func New(msg string) error
- func NewWithStack(msg string) error
- func PlainWith[T any](msg string, s ...T) error
- func Suppress(fn func() error, catch func(error)) func()
- func Unwrap(err error) error
- func WithAppend[T any](err error, s ...T) error
- func WithFirst[T any](err error, v T) error
- func WithLast[T any](err error, v T) error
- func WithMessage(err error, msg string) error
- func WithMessagef(err error, msg string, args ...interface{}) error
- func WithStack(err error) error
- func WithStackSkip(err error, skip int) error
- func Wrap(err error, msg string) error
- func Wrapf(err error, format string, args ...interface{}) error
- type Errors
- type Message
- type String
- type SyncErrors
Constants ¶
This section is empty.
Variables ¶
var ErrUnsupported = stderrors.ErrUnsupported
ErrUnsupported indicates an unsupported operation. This wraps errors.ErrUnsupported from the standard library.
Functions ¶
func As ¶
As finds the first error in err's chain that matches target type. This wraps errors.As from the standard library.
func Attachment ¶
Attachment retrieves a typed value attached to an error. Returns the value and true if found, or zero value and false otherwise.
Example:
err := WithFirst(errors.New("failed"), UserID("user123"))
if id, ok := Attachment[UserID](err); ok {
// use id
}
func Errorf ¶
Errorf creates a new error with a formatted message and stack trace. Similar to fmt.Errorf but includes stack trace information.
func Ignore ¶
func Ignore(error)
Ignore is an error handler that does nothing. Useful as a placeholder.
Example:
defer Suppress(file.Close, Ignore)()
func Is ¶
Is reports whether any error in err's chain matches target. This wraps errors.Is from the standard library.
func Join ¶
Join returns an error that wraps the given errors. This wraps errors.Join from the standard library (Go 1.20+).
func Must ¶
Must returns the value if err is nil, otherwise panics with the error. This is useful for initialization code where errors should be fatal.
Example:
config := Must(LoadConfig())
func New ¶
New creates a new error with the given message. This wraps errors.New from the standard library.
func NewWithStack ¶
NewWithStack creates a new error with the given message and stack trace.
func PlainWith ¶
PlainWith creates a new error with the given message and attached values.
Example:
err := PlainWith("operation failed", RequestID("req-123"))
func Suppress ¶
Suppress wraps a function that returns an error, calling catch if an error occurs. Returns a function that can be used with defer or other contexts.
Example:
defer Suppress(file.Close, func(err error) { log.Println(err) })()
func Unwrap ¶
Unwrap returns the result of calling the Unwrap method on err. This wraps errors.Unwrap from the standard library.
func WithAppend ¶
WithAppend attaches one or more values to an error, appending them to any existing values of the same type. Returns the original error if it's nil or no values are provided. Multiple values of the same type are stored as a slice.
Example:
err = WithAppend(err, slog.String("key", "value"))
err = WithAppend(err, slog.Int("count", 42))
func WithFirst ¶
WithFirst attaches a value to an error if no value of that type exists yet. If a value of the same type is already attached, it's preserved (first-wins). Returns nil if err is nil.
func WithLast ¶
WithLast attaches a value to an error, replacing any existing value of that type. This is a last-wins strategy for attachments. Returns nil if err is nil.
func WithMessage ¶
WithMessage attaches a contextual message to an error. Multiple messages are chained together and displayed in order.
Example:
err = WithMessage(err, "database query failed")
func WithMessagef ¶
WithMessagef attaches a formatted contextual message to an error. This is a convenience wrapper around WithMessage with fmt.Sprintf.
func WithStack ¶
WithStack attaches a stack trace to the error if one doesn't already exist. The stack trace is captured from the caller's location.
Example:
return WithStack(err)
func WithStackSkip ¶
WithStackSkip attaches a stack trace to the error, skipping the specified number of frames. This is useful for wrapper functions that want to exclude themselves from the trace.
Types ¶
type Errors ¶
type Errors []error
Errors is a slice of errors that can be treated as a single error. It provides methods for collecting and managing multiple errors.
Example:
var errs Errors errs.Collect(task1()) errs.Collect(task2()) return errs.Err() // returns nil, single error, or the Errors itself
func (*Errors) Collect ¶
Collect appends a non-nil error to the slice. This is useful for accumulating errors in a loop.
Example:
for _, item := range items {
errs.Collect(process(item))
}
func (Errors) Err ¶
Err returns the errors as a single error value, preserving the Errors type. Returns nil if empty, the single error if length is 1, or the Errors slice itself otherwise.
The returned Errors type deliberately does not implement Unwrap(), so errors.Is/As will not match against individual errors. This prevents accidentally matching one error while ignoring others, encouraging explicit iteration over all errors.
func (Errors) Error ¶
Error implements the error interface, summarising up to five of the contained errors.
type Message ¶
type Message string
Message is a string type used for error messages that can be attached to errors. Multiple messages form a chain that's displayed when formatting the error.
type String ¶
type String string
String is a constant error type. It implements the error interface and can be used for sentinel errors or simple error constants.
Example:
const ErrNotFound errors.String = "not found"
type SyncErrors ¶
type SyncErrors struct {
// contains filtered or unexported fields
}
SyncErrors is a thread-safe version of Errors for concurrent error collection.
func NewSyncErrors ¶
func NewSyncErrors() *SyncErrors
NewSyncErrors creates a new thread-safe error collector. Use this when collecting errors from concurrent goroutines.
Example:
errs := NewSyncErrors()
var wg sync.WaitGroup
for _, item := range items {
wg.Add(1)
go func(i Item) {
defer wg.Done()
errs.Collect(process(i))
}(item)
}
wg.Wait()
return errs.Err()
func (*SyncErrors) Collect ¶
func (s *SyncErrors) Collect(err error)
Collect appends a non-nil error to the slice in a thread-safe manner. Safe to call from multiple goroutines concurrently.
func (*SyncErrors) Err ¶
func (s *SyncErrors) Err() error
Err is the thread-safe equivalent of Errors.Err.
func (*SyncErrors) Error ¶
func (s *SyncErrors) Error() string
Error implements the error interface. It is the thread-safe equivalent of Errors.Error.
func (*SyncErrors) Format ¶
func (s *SyncErrors) Format(f fmt.State, verb rune)
Format implements fmt.Formatter. It is the thread-safe equivalent of Errors.Format.
func (*SyncErrors) Join ¶
func (s *SyncErrors) Join() error
Join is the thread-safe equivalent of Errors.Join.