errors

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 31, 2026 License: MIT Imports: 9 Imported by: 4

Documentation

Overview

Package errors extends the standard errors package with stack traces, typed attachments, and enhanced error formatting capabilities.

Index

Constants

This section is empty.

Variables

View Source
var ErrUnsupported = stderrors.ErrUnsupported

ErrUnsupported indicates an unsupported operation. This wraps errors.ErrUnsupported from the standard library.

Functions

func As

func As(err error, target any) bool

As finds the first error in err's chain that matches target type. This wraps errors.As from the standard library.

func Attachment

func Attachment[T any](err error) (v T, ok bool)

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

func Errorf(format string, args ...interface{}) error

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

func Is(err, target error) bool

Is reports whether any error in err's chain matches target. This wraps errors.Is from the standard library.

func Join

func Join(errs ...error) error

Join returns an error that wraps the given errors. This wraps errors.Join from the standard library (Go 1.20+).

func Must

func Must[T any](v T, err error) T

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

func New(msg string) error

New creates a new error with the given message. This wraps errors.New from the standard library.

func NewWithStack

func NewWithStack(msg string) error

NewWithStack creates a new error with the given message and stack trace.

func PlainWith

func PlainWith[T any](msg string, s ...T) error

PlainWith creates a new error with the given message and attached values.

Example:

err := PlainWith("operation failed", RequestID("req-123"))

func Suppress

func Suppress(fn func() error, catch func(error)) func()

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

func Unwrap(err error) error

Unwrap returns the result of calling the Unwrap method on err. This wraps errors.Unwrap from the standard library.

func WithAppend

func WithAppend[T any](err error, s ...T) error

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

func WithFirst[T any](err error, v T) error

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

func WithLast[T any](err error, v T) error

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

func WithMessage(err error, msg string) error

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

func WithMessagef(err error, msg string, args ...interface{}) error

WithMessagef attaches a formatted contextual message to an error. This is a convenience wrapper around WithMessage with fmt.Sprintf.

func WithStack

func WithStack(err error) error

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

func WithStackSkip(err error, skip int) error

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.

func Wrap

func Wrap(err error, msg string) error

Wrap wraps an error with an additional message and stack trace. Returns nil if err is nil.

Example:

if err := doSomething(); err != nil {
    return Wrap(err, "failed to do something")
}

func Wrapf

func Wrapf(err error, format string, args ...interface{}) error

Wrapf wraps an error with a formatted message and stack trace. Returns nil if err is nil.

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

func (e *Errors) Collect(err error)

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

func (e Errors) Err() error

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

func (e Errors) Error() string

Error implements the error interface, summarising up to five of the contained errors.

func (Errors) Format

func (e Errors) Format(f fmt.State, verb rune)

Format implements fmt.Formatter for rich error output. With %+v it prints each individual error on its own line.

func (Errors) Join

func (e Errors) Join() error

Join combines all errors using errors.Join from the standard library. Returns nil if empty, the single error if length is 1, or a joined error otherwise. The joined error supports errors.Is/As across all wrapped 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"

func (String) Error

func (s String) Error() string

func (String) WithStack

func (s String) WithStack() error

WithStack returns the error with a stack trace attached, captured from the caller.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL