errors

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: May 15, 2024 License: MIT Imports: 4 Imported by: 12

README

Errors - drop-in replacement for the stdlib errors package that adds wrapping and call stacks

Go Reference Go Report Card Tests Coverage Status

This is errors, a drop-in replacement for the standard Go errors package. It adds an API for wrapping an error with a caller-specified message and a snapshot of the call stack. It also adds a function for traversing an error’s tree of wrapped sub-errors.

This module began as a fork of the venerable github.com/pkg/errors. That module’s GitHub repository has been frozen for a long time and has not kept up with changes to the standard library. (For example, it does not export the Join function added in Go 1.20.)

This is now a brand-new implementation with a different API.

Usage

When you write code that handles an error from a function call by returning the error to your caller, it’s a good practice to “wrap” the error with context from your callsite first. The Go standard library lets you do this like so:

if err := doThing(...); err != nil {
  return fmt.Errorf("doing thing: %w", err)
}

The resulting error still “is” err (in the sense of errors.Is) but is now wrapped with context about how err was produced − to wit, “doing thing.”

This library lets you do the same thing like this:

if err := doThing(...); err != nil {
  return errors.Wrap(err, "doing thing")
}

This approach has a couple of benefits over wrapping with fmt.Errorf and %w. First, as a convenience, Wrap returns nil if its error argument is nil. So if doThing is the last thing that happens in your function, you can safely write:

err := doThing(...)
return errors.Wrap(err, "doing thing")

This will correctly return nil when doThing succeeds.

Second, errors produced by this package contain a snapshot of the call stack from the moment the error was created. This can be retrieved with the Stack function.

Note that diligent error wrapping often makes the stack trace superfluous. As errors work their way up the stack it’s possible to decorate them with enough extra context to understand exactly where and why the error occurred. But you can’t always rely on diligent error wrapping, and you can’t always wait for an error to propagate all the way up the call stack before reporting it.

Documentation

Overview

Package errors is a drop-in replacement for the stdlib errors package. It adds error-wrapping functions, stack traces, error-tree traversal.

Index

Constants

This section is empty.

Variables

View Source
var ErrSkip = New("skip")

ErrSkip can be used by the callback to Walk to skip an error's subtree without aborting the walk.

View Source
var ErrUnsupported = errors.ErrUnsupported

ErrUnsupported indicates that a requested operation cannot be performed, because it is unsupported. For example, a call to os.Link when using a file system that does not support hard links.

Functions and methods should not return this error but should instead return an error including appropriate context that satisfies

errors.Is(err, errors.ErrUnsupported)

either by directly wrapping ErrUnsupported or by implementing an Is method.

Functions and methods should document the cases in which an error wrapping this will be returned.

Functions

func As

func As(err error, target any) bool

As finds the first error in err's tree that matches target, and if one is found, sets target to that error value and returns true. Otherwise, it returns false.

The tree consists of err itself, followed by the errors obtained by repeatedly calling Unwrap. When err wraps multiple errors, As examines err followed by a depth-first traversal of its children.

An error matches target if the error's concrete value is assignable to the value pointed to by target, or if the error has a method As(any) bool such that As(target) returns true. In the latter case, the As method is responsible for setting target.

An error type might provide an As method so it can be treated as if it were a different error type.

As panics if target is not a non-nil pointer to either a type that implements error, or to any interface type.

func Errorf

func Errorf(format string, args ...any) error

Errorf is a synonym for Newf.

func Is

func Is(err, target error) bool

Is reports whether any error in err's tree matches target.

The tree consists of err itself, followed by the errors obtained by repeatedly calling Unwrap. When err wraps multiple errors, Is examines err followed by a depth-first traversal of its children.

An error is considered to match a target if it is equal to that target or if it implements a method Is(error) bool such that Is(target) returns true.

An error type might provide an Is method so it can be treated as equivalent to an existing error. For example, if MyError defines

func (m MyError) Is(target error) bool { return target == fs.ErrExist }

then Is(MyError{}, fs.ErrExist) returns true. See syscall.Errno.Is for an example in the standard library. An Is method should only shallowly compare err and the target and not call Unwrap on either.

func Join

func Join(errs ...error) error

Join returns an error that wraps the given errors. Any nil error values are discarded. Join returns nil if every value in errs is nil. The error formats as the concatenation of the strings obtained by calling the Error method of each element of errs, with a newline between each string.

A non-nil error returned by Join implements the Unwrap() []error method.

func New

func New(text string) error

New returns an error that formats as the given text. Each call to New returns a distinct error value even if the text is identical.

func Newf added in v1.0.0

func Newf(format string, args ...any) error

Newf creates a new error with the given format string and arguments, formatted as with fmt.Errorf. The result is a wrapped error containing the message and a stack trace. The format specifier %w works as in fmt.Errorf.

func Unwrap

func Unwrap(err error) error

Unwrap returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.

Unwrap only calls a method of the form "Unwrap() error". In particular Unwrap does not unwrap errors returned by Join.

func Walk added in v1.0.0

func Walk(e error, f func(error) error) error

Walk walks the error tree of e, calling f on each error found. If f returns a non-nil error, Walk stops and returns that error, unless the error is ErrSkip, in which case the walk skips e's children but otherwise continues without error.

The error tree of e consists of e itself and any children obtained by calling e's optional Unwrap method (whose return type may be error or []error), recursively.

The nodes of this tree are visited in a preorder, depth-first traversal.

func Wrap

func Wrap(err error, msg string) error

Wrap creates a wrapped error. It wraps the given error and attaches the given message. It may also attach a stack trace, but only if err doesn't already contain one. If err is nil, Wrap returns nil.

func Wrapf

func Wrapf(err error, format string, args ...any) error

Wrapf creates a wrapped error. It wraps the given error and attaches the message that results from formatting format with args. It may also attach a stack trace, but only if err doesn't already contain one. The format string may include %w specifiers, which work as in fmt.Errorf. If any errors included via %w include a stack trace, that will also prevent Wrapf from including a new one. If err is nil, Wrapf returns nil.

Types

type Frame

type Frame struct {
	Function, File string
	Line           int
}

Frame is a stack frame.

func (Frame) String added in v1.0.0

func (f Frame) String() string

type Frames added in v1.0.0

type Frames []Frame

Frames is a slice of Frame.

func Stack added in v1.0.0

func Stack(e error) Frames

Stack returns the stack trace from an error as a Frames. If the error is nil or does not contain a stack trace, Stack returns nil.

func (Frames) String added in v1.0.0

func (fs Frames) String() string

type Stacker added in v1.0.0

type Stacker interface {
	Stack() []uintptr
}

Stacker is the interface implemented by errors with a stack trace. Types wishing to implement Stacker can use runtime.Callers to get the call stack.

Jump to

Keyboard shortcuts

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