Documentation ¶
Overview ¶
Package errors provides simple error handling primitives.
The traditional error handling idiom in Go is roughly akin to
if err != nil { return err }
which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error.
Adding context to an error ¶
The errors.Annotate function returns a new error that adds context to the original error by recording a stack trace at the point Annotate is called, and the supplied message. For example
_, err := ioutil.ReadAll(r) if err != nil { return errors.Annotate(err, "read failed") }
If additional control is required the errors.AddStack and errors.WithMessage functions destructure errors.Annotate into its component operations of annotating an error with a stack trace and an a message, respectively.
Retrieving the cause of an error ¶
Using errors.Annotate constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Annotate to retrieve the original error for inspection. Any error value which implements this interface
type causer interface { Cause() error }
can be inspected by errors.Cause. errors.Cause will recursively retrieve the topmost error which does not implement causer, which is assumed to be the original cause. For example:
switch err := errors.Cause(err).(type) { case *MyError: // handle specifically default: // unknown error }
causer interface is not exported by this package, but is considered a part of stable public API. errors.Unwrap is also available: this will retrieve the next error in the chain.
Formatted printing of errors ¶
All error values returned from this package implement fmt.Formatter and can be formatted by the fmt package. The following verbs are supported
%s print the error. If the error has a Cause it will be printed recursively %v see %s %+v extended format. Each Frame of the error's StackTrace will be printed in detail.
Retrieving the stack trace of an error or wrapper ¶
New, Errorf, Annotate, and Annotatef record a stack trace at the point they are invoked. This information can be retrieved with the StackTracer interface that returns a StackTrace. Where errors.StackTrace is defined as
type StackTrace []Frame
The Frame type represents a call site in the stack trace. Frame supports the fmt.Formatter interface that can be used for printing information about the stack trace of this error. For example:
if stacked := errors.GetStackTracer(err); stacked != nil { for _, f := range stacked.StackTrace() { fmt.Printf("%+s:%d\n", f, f) } }
See the documentation for Frame.Format for more details.
errors.Find can be used to search for an error in the error chain.
Index ¶
- Variables
- func AddStack(err error) error
- func Annotate(err error, message string) error
- func Cause(err error) error
- func ErrorEqual(err1, err2 error) bool
- func ErrorNotEqual(err1, err2 error) bool
- func Errorf(format string, args ...interface{}) error
- func Errors(err error) []error
- func Find(origErr error, test func(error) bool) error
- func HasStack(err error) bool
- func New(message string) error
- func RedactErrorArg(args []interface{}, position []int)
- func SuspendStack(err error) error
- func Trace(err error) error
- func Unwrap(err error) error
- func WalkDeep(err error, visitor func(err error) bool) bool
- func WithMessage(err error, message string) error
- func WithStack(err error) error
- func Wrap(err error, message string) error
- func Wrapf(err error, format string, args ...interface{}) error
- type ErrCode
- type ErrCodeText
- type Error
- func (e *Error) Args() []interface{}
- func (e *Error) Cause() error
- func (e *Error) Code() ErrCode
- func (e *Error) Equal(err error) bool
- func (e *Error) Error() string
- func (e *Error) FastGen(format string, args ...interface{}) error
- func (e *Error) FastGenByArgs(args ...interface{}) error
- func (e *Error) FastGenWithCause(args ...interface{}) error
- func (e *Error) GenWithStack(format string, args ...interface{}) error
- func (e *Error) GenWithStackByArgs(args ...interface{}) error
- func (e *Error) GenWithStackByCause(args ...interface{}) error
- func (e *Error) GetMsg() string
- func (e *Error) ID() ErrorID
- func (e *Error) Is(other error) bool
- func (e *Error) Location() (file string, line int)
- func (e *Error) MessageTemplate() string
- func (e *Error) NotEqual(err error) bool
- func (e *Error) RFCCode() RFCErrorCode
- func (e *Error) Unwrap() error
- func (e *Error) Wrap(err error) *Error
- type ErrorGroup
- type ErrorID
- type Frame
- type NormalizeOption
- type RFCErrorCode
- type StackTrace
- type StackTraceAware
- type StackTracer
Constants ¶
This section is empty.
Variables ¶
var RedactLogEnabled atomic.Bool
RedactLogEnabled defines whether the arguments of Error need to be redacted.
Functions ¶
func AddStack ¶ added in v0.9.0
AddStack is similar to WithStack. However, it will first check with HasStack to see if a stack trace already exists in the causer chain before creating another one.
func Cause ¶
Cause returns the underlying cause of the error, if possible. An error value has a cause if it implements the following interface:
type causer interface { Cause() error }
If the error does not implement Cause, the original error will be returned. If the error is nil, nil will be returned without further investigation.
func ErrorEqual ¶ added in v0.11.5
ErrorEqual returns a boolean indicating whether err1 is equal to err2.
func ErrorNotEqual ¶ added in v0.11.5
ErrorNotEqual returns a boolean indicating whether err1 isn't equal to err2.
func Errorf ¶ added in v0.3.0
Errorf formats according to a format specifier and returns the string as a value that satisfies error. Errorf also records the stack trace at the point it was called.
func Errors ¶ added in v0.10.0
Errors uses the ErrorGroup interface to return a slice of errors. If the ErrorGroup interface is not implemented it returns an array containing just the given error.
func Find ¶ added in v0.9.0
Find an error in the chain that matches a test function. returns nil if no error is found.
func New ¶
New returns an error with the supplied message. New also records the stack trace at the point it was called.
func RedactErrorArg ¶ added in v0.11.5
func RedactErrorArg(args []interface{}, position []int)
RedactErrorArg redacts the args by position if RedactLogEnabled is enabled.
func SuspendStack ¶ added in v0.11.3
SuspendStack suspends stack for a exists error. it can be used to suspend follow up Trace do not add stack.
func Unwrap ¶ added in v0.9.0
Unwrap uses causer to return the next error in the chain or nil. This goes one-level deeper, whereas Cause goes as far as possible
func WalkDeep ¶ added in v0.9.0
WalkDeep does a depth-first traversal of all errors. Any ErrorGroup is traversed (after going deep). The visitor function can return true to end the traversal early In that case, WalkDeep will return true, otherwise false.
func WithMessage ¶ added in v0.8.0
WithMessage annotates err with a new message. If err is nil, WithMessage returns nil.
func WithStack ¶ added in v0.8.0
WithStack annotates err with a stack trace at the point WithStack was called. If err is nil, WithStack returns nil.
For most use cases this is deprecated and AddStack should be used (which will ensure just one stack trace). However, one may want to use this in some situations, for example to create a 2nd trace across a goroutine.
func Wrap ¶
Wrap returns an error annotating err with a stack trace at the point Wrap is called, and the supplied message. If err is nil, Wrap returns nil.
For most use cases this is deprecated in favor of Annotate. Annotate avoids creating duplicate stack traces.
Types ¶
type ErrCode ¶ added in v0.11.5
type ErrCode int
ErrCode represents a specific error type in a error class. Same error code can be used in different error classes.
type ErrCodeText ¶ added in v0.11.5
type ErrCodeText string
ErrCodeText is a textual error code that represents a specific error type in a error class.
type Error ¶ added in v0.11.5
type Error struct {
// contains filtered or unexported fields
}
Error is the 'prototype' of a type of errors. Use DefineError to make a *Error: var ErrUnavailable = errors.Normalize("Region %d is unavailable", errors.RFCCodeText("Unavailable"))
"throw" it at runtime:
func Somewhat() error { ... if err != nil { // generate a stackful error use the message template at defining, // also see FastGen(it's stackless), GenWithStack(it uses custom message template). return ErrUnavailable.GenWithStackByArgs(region.ID) } }
testing whether an error belongs to a prototype:
if ErrUnavailable.Equal(err) { // handle this error. }
func Normalize ¶ added in v0.11.5
func Normalize(message string, opts ...NormalizeOption) *Error
Normalize creates a new Error object.
func (*Error) Args ¶ added in v0.11.5
func (e *Error) Args() []interface{}
Args returns the message arguments of this error.
func (*Error) Code ¶ added in v0.11.5
Code returns the numeric code of this error. ID() will return textual error if there it is, when you just want to get the purely numeric error (e.g., for mysql protocol transmission.), this would be useful.
func (*Error) FastGen ¶ added in v0.11.5
FastGen generates a new *Error with the same class and code, and a new formatted message. This will not call runtime.Caller to get file and line.
func (*Error) FastGenByArgs ¶ added in v0.11.5
FastGen generates a new *Error with the same class and code, and a new arguments. This will not call runtime.Caller to get file and line.
func (*Error) FastGenWithCause ¶ added in v0.11.5
func (*Error) GenWithStack ¶ added in v0.11.5
GenWithStack generates a new *Error with the same class and code, and a new formatted message.
func (*Error) GenWithStackByArgs ¶ added in v0.11.5
GenWithStackByArgs generates a new *Error with the same class and code, and new arguments.
func (*Error) GenWithStackByCause ¶ added in v0.11.5
func (*Error) Is ¶ added in v0.11.5
Is checks if e has the same error ID with other. It allows Error to work with errors.Is() from the Go standard package.
func (*Error) Location ¶ added in v0.11.5
Location returns the location where the error is created, implements juju/errors locationer interface.
func (*Error) MessageTemplate ¶ added in v0.11.5
MessageTemplate returns the error message template of this error.
func (*Error) RFCCode ¶ added in v0.11.5
func (e *Error) RFCCode() RFCErrorCode
Code returns ErrorCode, by the RFC:
The error code is a 3-tuple of abbreviated component name, error class and error code, joined by a colon like {Component}:{ErrorClass}:{InnerErrorCode}.
type ErrorGroup ¶ added in v0.9.0
type ErrorGroup interface {
Errors() []error
}
ErrorGroup is an interface for multiple errors that are not a chain. This happens for example when executing multiple operations in parallel.
type Frame ¶ added in v0.6.0
type Frame uintptr
Frame represents a program counter inside a stack frame.
func (Frame) Format ¶ added in v0.6.0
Format formats the frame according to the fmt.Formatter interface.
%s source file %d source line %n function name %v equivalent to %s:%d
Format accepts flags that alter the printing of some verbs, as follows:
%+s function name and path of source file relative to the compile time GOPATH separated by \n\t (<funcname>\n\t<path>) %+v equivalent to %+s:%d
type NormalizeOption ¶ added in v0.11.5
type NormalizeOption func(*Error)
func MySQLErrorCode ¶ added in v0.11.5
func MySQLErrorCode(code int) NormalizeOption
MySQLErrorCode returns a NormalizeOption to set error code.
func RFCCodeText ¶ added in v0.11.5
func RFCCodeText(codeText string) NormalizeOption
RFCCodeText returns a NormalizeOption to set RFC error code.
func RedactArgs ¶ added in v0.11.5
func RedactArgs(pos []int) NormalizeOption
type RFCErrorCode ¶ added in v0.11.5
type RFCErrorCode string
type StackTrace ¶ added in v0.7.0
type StackTrace []Frame
StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
func (StackTrace) Format ¶ added in v0.7.0
func (st StackTrace) Format(s fmt.State, verb rune)
Format formats the stack of Frames according to the fmt.Formatter interface.
%s lists source files for each Frame in the stack %v lists the source file and line number for each Frame in the stack
Format accepts flags that alter the printing of some verbs, as follows:
%+v Prints filename, function, and line number for each Frame in the stack.
type StackTraceAware ¶ added in v0.9.0
type StackTraceAware interface {
HasStack() bool
}
StackTraceAware is an optimization to avoid repetitive traversals of an error chain. HasStack checks for this marker first. Annotate/Wrap and Annotatef/Wrapf will produce this marker.
type StackTracer ¶ added in v0.9.0
type StackTracer interface {
StackTrace() StackTrace
}
StackTracer retrieves the StackTrace Generally you would want to use the GetStackTracer function to do that.
func GetStackTracer ¶ added in v0.9.0
func GetStackTracer(origErr error) StackTracer
GetStackTracer will return the first StackTracer in the causer chain. This function is used by AddStack to avoid creating redundant stack traces.
You can also use the StackTracer interface on the returned error to get the stack trace.
func NewStack ¶ added in v0.9.0
func NewStack(skip int) StackTracer
NewStack is for library implementers that want to generate a stack trace. Normally you should insted use AddStack to get an error with a stack trace.
The result of this function can be turned into a stack trace by calling .StackTrace()
This function takes an argument for the number of stack frames to skip. This avoids putting stack generation function calls like this one in the stack trace. A value of 0 will give you the line that called NewStack(0) A library author wrapping this in their own function will want to use a value of at least 1.