Documentation ¶
Overview ¶
Package errors contains additional functions, interfaces and structs for recording stack frames, applying basic formatting, working with goroutines, multiple errors and custom error types.
It is inspired by package golang.org/x/xerrors and is designed to be a drop-in replacement for it, as well as the standard library's errors package.
The New and Newf functions create errors whose content is a text message and whom can trace stack frames. Wrap and Wrapf create errors by wrapping an existing error with a similar error like New and Newf.
StackTrace tracing ¶
Every error can track stack trace information. Just wrap it with errors.WithStack and a complete stack trace is captured.
err = errors.WithStack(err)
Printing the error results in a trace similar to:
some error: something happened: main.main /go-pogo/errors/.examples/3_with_kind/main.go:24 main.doSomething /go-pogo/errors/.examples/3_with_kind/main.go:20 main.someAction /go-pogo/errors/.examples/3_with_kind/main.go:16
Formatting ¶
Wrap an existing error with errors.WithFormatter to upgrade the error to include basic formatting. Formatting is done using xerrors.FormatError and thus the same verbs are supported.
mt.Printf("%+v", errors.WithFormatter(err))
Catching panics ¶
A convenient function is available to catch panics and store them as an error.
var err error defer errors.CatchPanic(&err)
Backwards compatibility ¶
Unwrap, Is, As are backwards compatible with the standard library's errors package and act the same.
Index ¶
- Variables
- func Append(dest *error, errs ...error)
- func AppendFunc(dest *error, fn func() error)
- func As(err error, target interface{}) bool
- func Callers(skipFrames uint, dest *[]xerrors.Frame) int
- func CatchPanic(dest *error)
- func Cause(err error) error
- func Combine(errors ...error) error
- func FatalOnErr(err error)
- func Filter(errors []error) []error
- func FormatError(err error, state fmt.State, verb rune)
- func GetExitCode(err error) int
- func GetExitCodeOr(err error, or int) int
- func GetTime(err error) (time.Time, bool)
- func Is(err, target error) bool
- func Must(args ...interface{})
- func New(msg interface{}) error
- func Newf(format string, args ...interface{}) error
- func Opaque(err error) error
- func PrintError(printer xerrors.Printer, err error)
- func Unembed(err error) error
- func Unwrap(err error) error
- func UnwrapAll(err error) []error
- func WithFormatter(err error) xerrors.Formatter
- func WithKind(err error, kind Kind) error
- func Wrap(cause error, msg interface{}) error
- func WrapPanic(prefix string)
- func Wrapf(cause error, format string, args ...interface{}) error
- type Embedder
- type ErrorLister
- type ExitCoder
- type ExitCoderSetter
- type Kind
- type List
- type Msg
- type MultiError
- type StackTrace
- type StackTracer
- type Timer
- type TimerSetter
- type UnsupportedTypeError
- type WaitGroup
- type Wrapper
Constants ¶
This section is empty.
Variables ¶
var DefaultListCapacity uint = 8
Functions ¶
func Append ¶
Append appends multiple non-nil errors to a single multi error dest. When the value of dest is nil and errs only contains a single error, its value is set to the value of dest.
Important: when using Append with defer, the pointer to the dest error must be a named return variable. For additional details see https://golang.org/ref/spec#Defer_statements.
func AppendFunc ¶ added in v0.7.2
AppendFunc appends the non-nil error result of fn to dest using Append.
func As ¶
As is an alias of errors.As. It finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.
func Callers ¶ added in v0.7.0
Callers fills the stack *StackTrace with xerrors.Frame's from the point Callers is called, skipping the first skipFrames frames.
func CatchPanic ¶ added in v0.6.0
func CatchPanic(dest *error)
CatchPanic recovers from a panic and wraps it in an error. It then calls Append with the provided dest *error and wrapped panic. Use CatchPanic directly with defer. It is not possible to use CatchPanic inside a deferred function, like:
defer func(){ CatchPanic(&err }()
func Cause ¶ added in v0.7.0
Cause walks through all wrapped errors and returns the last error in the chain.
func Combine ¶
Combine returns a MultiError when more than one non-nil errors are provided. It returns a single error when only one error is passed, and nil if no non-nil errors are provided.
func FatalOnErr ¶ added in v0.7.2
func FatalOnErr(err error)
FatalOnErr prints the error to stderr and exits the program with an exit code that is not 0. When err is an ExitCoder its exit code is used.
func Filter ¶
Filter returns a slice of errors without nil values in between them. It returns the slice with the length of the amount of non-nil errors but keeps its original capacity.
func FormatError ¶
FormatError calls the FormatError method of err with a xerrors.Printer configured according to state and verb, and writes the result to state. It will wrap err If err is not a xerrors.Formatter it will wrap err, so it is capable of basic error formatting using WithFormatter.
func GetExitCode ¶
GetExitCode returns an exit status code if the error implements the ExitCoder interface. If not, it returns 0.
func GetExitCodeOr ¶ added in v0.6.1
GetExitCodeOr returns the exit status code from the first found ExitCoder in err's error chain. If none is found, it returns the provided value or.
func GetTime ¶ added in v0.7.0
GetTime returns the time.Time of the last found Timer in err's error chain. If none is found, it returns the provided value or.
func Is ¶
Is reports whether any error in err's chain matches target. It is fully compatible with both errors.Is and xerrors.Is.
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.
func Must ¶
func Must(args ...interface{})
Must panics when any of the given args is a non-nil error. Its message is the error message of the first encountered error.
func New ¶
func New(msg interface{}) error
New creates a new error which implements the StackTracer, Wrapper and xerrors.Formatter interfaces. Argument msg can be either a string or Msg.
err := errors.New("my error message") err := errors.New(errors.Msg("my error message"))
New records a stack trace at the point it was called. Each call returns a distinct error value even if msg is identical. It will return nil if msg is nil. Use WithStack to wrap an existing error with a StackTracer and xerrors.Formatter.
func Newf ¶
Newf formats an error message according to a format specifier and provided arguments with fmt.Errorf, and creates a new error similar to New.
err := errors.Newf("my error %s", "message") err := errors.Newf("my error: %w", cause)
func Opaque ¶
Opaque is an alias of xerrors.Opaque. It returns an error with the same error formatting as err but that does not match err and cannot be unwrapped.
func PrintError ¶
PrintError prints the error err with the provided xerrors.Printer and additionally formats and prints the error's stack frames.
func Unembed ¶ added in v0.7.0
Unembed recursively unwraps all Embedder errors and returns the (original) error that was wrapped with extra context. If err is not an Embedder, Unembed returns err as provided.
func Unwrap ¶
Unwrap is an alias of errors.Unwrap. It returns the result of calling the Unwrap method on err, if err's type contains an Unwrap method returning error. Otherwise, Unwrap returns nil.
func UnwrapAll ¶
UnwrapAll returns the complete chain of errors, starting with the supplied error and ending with the root cause error.
func WithFormatter ¶
WithFormatter wraps the error with a xerrors.Formatter that is capable of basic error formatting. It returns the provided error as is if it already is a xerrors.Formatter, or nil when err is nil.
func Wrap ¶
Wrap creates a new error, which implements the StackTracer, Wrapper and xerrors.Formatter interfaces, that wraps around the causing error. Argument msg can be either a string or Msg.
err = errors.Wrap(err, "my error message") err = errors.Wrap(err, errors.Msg("my error message"))
Wrap records a stack trace at the point it was called. Each call returns a distinct error value even if cause and msg are identical. Wrap will return nil when cause is nil, and it will return the provided cause when msg is nil.
Types ¶
type ErrorLister ¶
type ErrorLister interface { // ErrorList returns a List of collected non-nil errors. ErrorList() *List }
type ExitCoder ¶
ExitCoder interfaces provide access to an exit code.
func WithExitCode ¶
WithExitCode adds an exit status code to the error which may indicate a fatal error. The exit code can be supplied to os.Exit to terminate the program immediately.
type ExitCoderSetter ¶ added in v0.7.0
type Kind ¶
type Kind string
Kind describes the kind/type of error that has occurred. For example "auth error", "unmarshal error", etc. Errors can be of the same Kind but still contain different underlying causes. It is recommended to define each Kind as a constant.
const UnknownKind Kind = ""
UnknownKind is the default Kind for errors that are created without a distinct Kind.
func GetKind ¶
GetKind returns the Kind of the error if it is added with WithKind. If not, it returns UnknownKind.
type List ¶
func (*List) Append ¶
Append an error to the list. It guarantees only non-nil errors are added. It returns false when a nil error is encountered. And true when the error is appended to the list.
func (*List) Combine ¶
Combine the collected errors. It uses the same rules and logic as the Combine function.
type Msg ¶ added in v0.7.0
type Msg string
Msg is a string alias which can also be used as a basic error. This is particularly useful for defining constants of known errors in your library or application.
const ErrMyErrorMessage errors.Msg = "my error message" const ErrAnotherError errors.Msg = "just another error"
A new error can be constructed from any Msg with New and is considered to be equal when comparing with Is.
err := errors.New(ErrMyErrorMessage) errors.Is(err, ErrMyErrorMessage) // true
type MultiError ¶
type StackTrace ¶ added in v0.7.0
type StackTrace struct { // Skip n frames when formatting with Format, so overlapping frames from // previous errors are not printed. Skip uint // contains filtered or unexported fields }
func GetStackTrace ¶ added in v0.7.0
func GetStackTrace(err error) *StackTrace
GetStackTrace returns a *StackTrace if err is a StackTracer or nil otherwise.
func (*StackTrace) Format ¶ added in v0.7.0
func (st *StackTrace) Format(printer xerrors.Printer)
Format formats the slice of xerrors.Frame using a xerrors.Printer.
func (*StackTrace) Frames ¶ added in v0.7.0
func (st *StackTrace) Frames() []xerrors.Frame
func (*StackTrace) Len ¶ added in v0.7.0
func (st *StackTrace) Len() uint
func (*StackTrace) String ¶ added in v0.7.0
func (st *StackTrace) String() string
type StackTracer ¶
type StackTracer interface { error // StackTrace returns a stack of traces frames. StackTrace() *StackTrace }
StackTracer interfaces provide access to a stack of traced StackTrace.
func WithStack ¶ added in v0.7.0
func WithStack(err error) StackTracer
WithStack gets a stack trace at the point WithStack was called and adds it to the error. If err is nil, WithStack returns nil.
type Timer ¶ added in v0.7.0
Timer interfaces provide access to a time.Time indicating when the error occurred.
type TimerSetter ¶ added in v0.7.0
type UnsupportedTypeError ¶ added in v0.7.0
type UnsupportedTypeError struct {
Func, Type string
}
func (*UnsupportedTypeError) Error ¶ added in v0.7.0
func (ut *UnsupportedTypeError) Error() string
type WaitGroup ¶
type WaitGroup struct {
// contains filtered or unexported fields
}
A WaitGroup is a collection of goroutines working on subtasks that are part of the same overall task. It collects possible errors returned from the subtasks and, unlike golang.org/x/sync/errgroup.Group, does not cancel the group when an error is encountered.
func (*WaitGroup) ErrorList ¶
ErrorList returns a List of collected errors from the called goroutines.