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 MustRegister(coder Coder)
- func New(message string) error
- func Reduce(err error) error
- func Register(coder Coder)
- 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 Coder
- 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 从输入错误中移除与任何匹配器匹配的所有错误。如果输入是单个错误,则只测试该错误。如果输入实现了 Aggregate 接口,错误列表将递归处理。 这可以用于从错误列表中移除已知的无害错误(例如 io.EOF 或 os.PathNotFound)
@Description: @param err @param fns @return error
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 MustRegister ¶
func MustRegister(coder Coder)
MustRegister 注册一个用户定义的错误代码。 如果相同的 Code 已经存在,它将会 panic
func New ¶
New 返回一条带有指定信息的错误信息 同时记录调用它时的堆栈跟踪信息
Example ¶
err := New("whoops") fmt.Println(err)
Output: whoops
Example (Printf) ¶
err := New("whoops") fmt.Printf("%+v", err)
Output:
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(codes[err.(*withCode).code].String()) 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 并行运行提供的函数,在返回的 Aggregate 中存储所有非空错误。如果所有函数都成功完成,则返回 nil
func CreateAggregateFromMessageCountMap ¶
func CreateAggregateFromMessageCountMap(m MessageCountMap) Aggregate
CreateAggregateFromMessageCountMap 将 MessageCountMap 包含每个错误消息的出现次数 重新转化为 err(repeated num times) 的 字符串数组 converts MessageCountMap Aggregate
@Description: @param m @return Aggregate
func Flatten ¶
Flatten 如果此 Aggregate 有着深度嵌套其他 Aggregate 让其扁平化 接受一个 Aggregate,该 Aggregate 可以包含任意嵌套的其他 Aggregate,并将它们全部递归展平为单个 Aggregate
@Description: @param agg @return Aggregate
func NewAggregate ¶
NewAggregate 将错误切片转化为 Aggregate 接口, 本身是 error 接口的实现. 如果切片为空, 那么返回 nil. 该函数会检查输入错误列表的任何元素是否为 nil, 以避免在调用 Error() 时发生空指针恐慌
type Coder ¶
type Coder interface { // HTTPStatus HTTP状态码,应该与相关的错误码一起使用 HTTPStatus() int // String 面向外部用户的错误文本 String() string // Reference 返回用户的详细文档 Reference() string // Code 返回该错误码的代码 Code() int }
Coder 定义了一个错误码详细信息的接口
func ParseCoder ¶
ParseCoder 将任何错误解析为*withCode 空错误将直接返回nil 没有堆栈信息的错误将被解析为 ErrUnknown
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 表示堆栈帧内的程序计数器。由于历史原因,如果将 Frame 解释为 uintptr,其值表示程序计数器 + 1
func (Frame) Format ¶
Format 方法按照 fmt.Formatter 接口的规定格式化堆栈帧
%s 打印源文件 %d 打印源代码行 %n 打印函数名 %v 等同于 %s:%d
Format 还支持以下标志:
%+s 打印函数名和源文件的路径,相对于编译时的 GOPATH,用 \n\t 分隔(<funcname>\n\t<path>) %+v 等同于 %+s:%d
func (Frame) MarshalText ¶
MarshalText 将堆栈追踪帧(Frame)格式化为文本字符串。输出与 fmt.Sprintf("%+v", f) 相同,但不包含换行符或制表符
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(codes[err.(*withCode).code].String())
Output: Load configuration file failed
func StringKeySet ¶
func StringKeySet(theMap interface{}) String
StringKeySet 从 map[string](? extends interface{}) 的键创建一个 String 如果传入的值实际上不是一个 map,这将引发 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 return 内容以随机顺序排列的切片