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 when 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.Wrap function returns a new error that adds context to the original error by recording a stack trace at the point Wrap is called, together with the supplied message. For example
_, err := ioutil.ReadAll(r) if err != nil { return errors.Wrap(err, "read failed") }
If additional control is required, the errors.WithStack and errors.WithMessage functions destructure errors.Wrap into its component operations: annotating an error with a stack trace and with a message, respectively.
Retrieving the cause of an error ¶
Using errors.Wrap 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.Wrap 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 that 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 }
Although the causer interface is not exported by this package, it is considered a part of its stable public interface.
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, Wrap, and Wrapf record a stack trace at the point they are invoked. This information can be retrieved with the following interface:
type stackTracer interface { StackTrace() errors.StackTrace }
The returned errors.StackTrace type 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 err, ok := err.(stackTracer); ok { for _, f := range err.StackTrace() { fmt.Printf("%+s:%d\n", f, f) } }
Although the stackTracer interface is not exported by this package, it is considered a part of its stable public interface.
See the documentation for Frame.Format for more details.
Example (StackTrace) ¶
type stackTracer interface { StackTrace() StackTrace } err, ok := Cause(fn()).(stackTracer) if !ok { panic("oops, err does not implement stackTracer") } st := err.StackTrace() fmt.Printf("%+v", st[0:2]) // top two frames
Output:
Index ¶
- Variables
- func As(err error, target interface{}) bool
- func Cause(err error) error
- func Code(err error) int
- func Errorf(format string, args ...interface{}) error
- func FilterOut(err error, fns ...Matcher) error
- func FromGrpcError(err error) error
- func Is(err, target error) bool
- func IsCode(err error, code int) bool
- func New(message string) error
- func ParseCoder(err error) code.Coder
- func Reduce(err error) error
- func ToGrpcError(err error) error
- func Unwrap(err error) error
- func WithCode(code int, format string, args ...interface{}) error
- func WithMessage(err error, message string) error
- func WithMessagef(err error, format string, args ...interface{}) error
- func WithStack(err error) error
- func Wrap(err error, message string) error
- func WrapC(err error, code int, format string, args ...interface{}) error
- func Wrapf(err error, format string, args ...interface{}) error
- type Aggregate
- type Empty
- type Frame
- type Matcher
- type MessageCountMap
- type StackTrace
- type String
- func (s String) Delete(items ...string) String
- func (s String) Difference(s2 String) String
- func (s String) Equal(s2 String) bool
- func (s String) Has(item string) bool
- func (s String) HasAll(items ...string) bool
- func (s String) HasAny(items ...string) bool
- func (s String) Insert(items ...string) String
- func (s String) Intersection(s2 String) String
- func (s String) IsSuperset(s2 String) bool
- func (s String) Len() int
- func (s String) List() []string
- func (s String) PopAny() (string, bool)
- func (s String) Union(s2 String) String
- func (s String) UnsortedList() []string
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrPreconditionViolated = errors.New("precondition is violated")
ErrPreconditionViolated 在违反前提条件时返回
Functions ¶
func As ¶
As finds the first error in err's chain that matches target, and if so, sets target to that error value and returns true.
The chain consists of err itself followed by the sequence of errors obtained by repeatedly calling Unwrap.
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(interface{}) bool such that As(target) returns true. In the latter case, the As method is responsible for setting target.
As will panic if target is not a non-nil pointer to either a type that implements error, or to any interface type. As returns false if err is nil.
func Cause ¶
Cause 返回错误的根本原因,如果可能的话。 如果一个错误值实现了以下接口,则它有一个原因: interface:
type causer interface { Cause() error }
如果错误没有实现Cause,则将返回原始错误。如果错误为nil,则不进行进一步的调查,直接返回nil。
Example ¶
err := fn() fmt.Println(err) fmt.Println(Cause(err))
Output: outer error
Example (Printf) ¶
err := Wrap(func() error { return func() error { return New("hello world") }() }(), "failed") fmt.Printf("%v", err)
Output: failed
func Errorf ¶
Errorf 根据格式说明符进行格式化并返回一个字符串,该字符串作为满足 error 的值。 在调用 Errorf 时也会记录堆栈跟踪。
Example (Extended) ¶
err := Errorf("whoops: %s", "foo") fmt.Printf("%+v", err)
Output:
func FilterOut ¶
FilterOut removes all errors that match any of the matchers from the input error. If the input is a singular error, only that error is tested. If the input implements the Aggregate interface, the list of errors will be processed recursively.
This can be used, for example, to remove known-OK errors (such as io.EOF or os.PathNotFound) from a list of errors.
func Is ¶
Is reports whether any error in err's chain matches target.
The chain consists of err itself followed by the sequence of errors obtained by repeatedly calling Unwrap.
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 New ¶
New 返回一条带有指定信息的错误信息 New 同时记录调用它时的堆栈跟踪信息
Example ¶
err := New("whoops") fmt.Println(err)
Output: whoops
Example (Printf) ¶
err := New("whoops") fmt.Printf("%+v", err)
Output:
func ParseCoder ¶
ParseCoder 将任何错误解析为*withCode 空错误将直接返回nil 没有堆栈信息的错误将被解析为 ErrUnknown
func Reduce ¶
Reduce will return err or, if err is an Aggregate and only has one item, the first item in the aggregate.
func Unwrap ¶
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.
func WithCode ¶
WithCode 生成 withCode 结构体
Example ¶
var err error err = WithCode(ConfigurationNotValid, "this is an error message") fmt.Println(err) err = Wrap(err, "this is a wrap error message with error code not change") fmt.Println(err) err = WrapC(err, ErrInvalidJSON, "this is a wrap error message with new error code") fmt.Println(code.Get(err.(*withCode).code).Message()) fmt.Println(err) //fmt.Printf("%+v\n", err) //fmt.Printf("%#+v\n", err)
Output: ConfigurationNotValid error ConfigurationNotValid error Data is not valid JSON Data is not valid JSON
func WithMessage ¶
WithMessage 用新消息注释err。 如果err为nil,则WithMessage返回nil。
Example ¶
cause := New("whoops") err := WithMessage(cause, "oh noes") fmt.Println(err)
Output: oh noes
func WithMessagef ¶
WithMessagef 使用格式说明符注释err 如果err为nil,则WithMessagef返回nil
func WithStack ¶
WithStack 函数会在调用 WithStack 的时候,为 err 添加一个堆栈跟踪。 如果 err 为 nil,则 WithStack 返回 nil。
Example ¶
cause := New("whoops") err := WithStack(cause) fmt.Println(err)
Output: whoops
Example (Printf) ¶
cause := New("whoops") err := WithStack(cause) fmt.Printf("%+v", err)
Output:
func Wrap ¶
Wrap 返回一个在调用Wrap时,使用堆栈跟踪注释err和提供的消息的错误。 如果err为nil,则Wrap返回nil。
Example ¶
cause := New("whoops") err := Wrap(cause, "oh noes") fmt.Println(err)
Output: oh noes
Example (Extended) ¶
err := fn() fmt.Printf("%+v\n", err)
Output:
Types ¶
type Aggregate ¶
Aggregate 表示包含多个错误的对象,但不一定具有单一的语义意义。 可以使用 errors.Is() 和聚合对象检查特定错误类型的出现。 不支持 Errors.As(),因为调用者可能关心与给定类型匹配的一个或多个特定错误。
func AggregateGoroutines ¶
AggregateGoroutines runs the provided functions in parallel, stuffing all non-nil errors into the returned Aggregate. Returns nil if all the functions complete successfully.
func CreateAggregateFromMessageCountMap ¶
func CreateAggregateFromMessageCountMap(m MessageCountMap) Aggregate
CreateAggregateFromMessageCountMap converts MessageCountMap Aggregate
func Flatten ¶
Flatten takes an Aggregate, which may hold other Aggregates in arbitrary nesting, and flattens them all into a single Aggregate, recursively.
func NewAggregate ¶
NewAggregate converts a slice of errors into an Aggregate interface, which is itself an implementation of the error interface. If the slice is empty, this returns nil. It will check if any of the element of input error list is nil, to avoid nil pointer panic when call Error().
type Empty ¶
type Empty struct{}
Empty is public since it is used by some internal API objects for conversions between external string arrays and internal sets, and conversion logic requires public types today.
type Frame ¶
type Frame uintptr
Frame represents a program counter inside a stack frame. For historical reasons if Frame is interpreted as a uintptr its value represents the program counter + 1.
func (Frame) Format ¶
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
func (Frame) MarshalText ¶
MarshalText formats a stacktrace Frame as a text string. The output is the same as that of fmt.Sprintf("%+v", f), but without newlines or tabs.
type StackTrace ¶
type StackTrace []Frame
StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
func (StackTrace) Format ¶
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 String ¶
String is a set of strings, implemented via map[string]struct{} for minimal memory consumption.
Example ¶
err := loadConfig() if nil != err { err = WrapC(err, ErrLoadConfigFailed, "failed to load configuration") } fmt.Println(code.Get(err.(*withCode).code).Message())
Output: Load configuration file failed
func StringKeySet ¶
func StringKeySet(theMap interface{}) String
StringKeySet creates a String from a keys of a map[string](? extends interface{}). If the value passed in is not actually a map, this will panic.
func (String) Difference ¶
Difference returns a set of objects that are not in s2 For example: s = {a1, a2, a3} s2 = {a1, a2, a4, a5} s.Difference(s2) = {a3} s2.Difference(s) = {a4, a5}
func (String) Equal ¶
Equal returns true if and only if s is equal (as a set) to s2. Two sets are equal if their membership is identical. (In practice, this means same elements, order doesn't matter)
func (String) Intersection ¶
Intersection returns a new set which includes the item in BOTH s and s2 For example: s = {a1, a2} s2 = {a2, a3} s.Intersection(s2) = {a2}
func (String) IsSuperset ¶
IsSuperset returns true if and only if s is a superset of s2.
func (String) Union ¶
Union returns a new set which includes items in either s or s2. For example: s = {a1, a2} s2 = {a3, a4} s.Union(s2) = {a1, a2, a3, a4} s2.Union(s) = {a1, a2, a3, a4}
func (String) UnsortedList ¶
UnsortedList returns the slice with contents in random order.