errors

package module
v0.0.0-...-355dc4f Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2024 License: MulanPSL-2.0 Imports: 15 Imported by: 0

README

基于 github.com/pkg/errors 包,增加对 error code 的支持,完全兼容 github.com/pkg/errors

性能跟 github.com/pkg/errors 基本持平。

该 errors 包匹配的错误码设计请参考:marmotedu/sample-code

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

Examples

Constants

This section is empty.

Variables

View Source
var ErrPreconditionViolated = errors.New("precondition is violated")

ErrPreconditionViolated 在违反前提条件时返回

Functions

func As

func As(err error, target interface{}) bool

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

func Cause(err error) error

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 Code

func Code(err error) int

Code

@Description: return errCode
@param err
@return int

func Errorf

func Errorf(format string, args ...interface{}) error

Errorf 根据格式说明符进行格式化并返回一个字符串,该字符串作为满足 error 的值。 在调用 Errorf 时也会记录堆栈跟踪。

Example (Extended)
err := Errorf("whoops: %s", "foo")
fmt.Printf("%+v", err)
Output:

func FilterOut

func FilterOut(err error, fns ...Matcher) error

FilterOut 从输入错误中移除与任何匹配器匹配的所有错误。如果输入是单个错误,则只测试该错误。如果输入实现了 Aggregate 接口,错误列表将递归处理。 这可以用于从错误列表中移除已知的无害错误(例如 io.EOF 或 os.PathNotFound)

@Description:
@param err
@param fns
@return error

func FromGrpcError

func FromGrpcError(err error) error

FromGrpcError grpcError 转换 Error

func Is

func Is(err, target error) bool

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 IsCode

func IsCode(err error, code int) bool

IsCode 函数会检查err链中是否包含给定的错误代码,如果有则返回true,否则返回false

func MustRegister

func MustRegister(coder Coder)

MustRegister 注册一个用户定义的错误代码。 如果相同的 Code 已经存在,它将会 panic

func New

func New(message string) error

New 返回一条带有指定信息的错误信息 同时记录调用它时的堆栈跟踪信息

Example
err := New("whoops")
fmt.Println(err)
Output:

whoops
Example (Printf)
err := New("whoops")
fmt.Printf("%+v", err)
Output:

func Reduce

func Reduce(err error) error

Reduce 将返回 err,或者如果 err 是一个 Aggregate 且只有一个项,则返回该 Aggregate 中的第一个项

func Register

func Register(coder Coder)

Register 用于注册自定义错误码。 如果注册的错误码已经存在,则会覆盖之前的错误码

func ToGrpcError

func ToGrpcError(err error) error

ToGrpcError Error 转换 grpcError

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.

func WithCode

func WithCode(code int, format string, args ...interface{}) error

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

func WithMessage(err error, message string) error

WithMessage 用新消息注释 err。 如果err为nil,则WithMessage返回nil。

Example
cause := New("whoops")
err := WithMessage(cause, "oh noes")
fmt.Println(err)
Output:

oh noes

func WithMessagef

func WithMessagef(err error, format string, args ...interface{}) error

WithMessagef 使用格式说明符注释 err 如果err为nil,则WithMessagef返回nil

func WithStack

func WithStack(err error) error

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

func Wrap(err error, message string) error

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:

func WrapC

func WrapC(err error, code int, format string, args ...interface{}) error

WrapC 生成 携带 子错误 的 withCode 结构体

func Wrapf

func Wrapf(err error, format string, args ...interface{}) error

Wrapf 返回一个在调用Wrapf时,使用堆栈跟踪注释err和格式说明符的错误。 如果err为nil,则Wrapf返回nil。

Example
cause := New("whoops")
err := Wrapf(cause, "oh noes #%d", 2)
fmt.Println(err)
Output:

oh noes #2

Types

type Aggregate

type Aggregate interface {
	error
	Errors() []error
	Is(error) bool
}

Aggregate 表示包含多个错误的对象,但不一定具有单一的语义意义。 可以使用 errors.Is() 和聚合对象检查特定错误类型的出现。 不支持 Errors.As(),因为调用者可能关心与给定类型匹配的一个或多个特定错误。

func AggregateGoroutines

func AggregateGoroutines(funcs ...func() error) Aggregate

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

func Flatten(agg Aggregate) Aggregate

Flatten 如果此 Aggregate 有着深度嵌套其他 Aggregate 让其扁平化 接受一个 Aggregate,该 Aggregate 可以包含任意嵌套的其他 Aggregate,并将它们全部递归展平为单个 Aggregate

@Description:
@param agg
@return Aggregate

func NewAggregate

func NewAggregate(errlist []error) Aggregate

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

func ParseCoder(err error) Coder

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

func (f Frame) Format(s fmt.State, verb rune)

Format 方法按照 fmt.Formatter 接口的规定格式化堆栈帧

%s    打印源文件
%d    打印源代码行
%n    打印函数名
%v    等同于 %s:%d

Format 还支持以下标志:

%+s   打印函数名和源文件的路径,相对于编译时的 GOPATH,用 \n\t 分隔(<funcname>\n\t<path>)
%+v   等同于 %+s:%d

func (Frame) MarshalText

func (f Frame) MarshalText() ([]byte, error)

MarshalText 将堆栈追踪帧(Frame)格式化为文本字符串。输出与 fmt.Sprintf("%+v", f) 相同,但不包含换行符或制表符

type Matcher

type Matcher func(error) bool

Matcher 用于匹配错误。如果错误匹配,则返回 true

type MessageCountMap

type MessageCountMap map[string]int

MessageCountMap 包含每个错误消息的出现次数

type StackTrace

type StackTrace []Frame

StackTrace 是先进先出的帧堆栈

func (StackTrace) Format

func (st StackTrace) Format(s fmt.State, verb rune)

Format 方法按照 fmt.Formatter 接口的规定格式化一组堆栈帧

%s	列出每个堆栈帧中的源文件
%v	列出每个堆栈帧中的源文件和行号

Format 还支持以下标志:

%+v   打印每个堆栈帧的文件名、函数和行号

type String

type String map[string]Empty

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 NewString

func NewString(items ...string) String

NewString 创建一个 String 来自数组

func StringKeySet

func StringKeySet(theMap interface{}) String

StringKeySet 从 map[string](? extends interface{}) 的键创建一个 String 如果传入的值实际上不是一个 map,这将引发 panic。

func (String) Delete

func (s String) Delete(items ...string) String

Delete removes all items from the set.

func (String) Difference

func (s String) Difference(s2 String) String

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

func (s String) Equal(s2 String) bool

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) Has

func (s String) Has(item string) bool

Has 返回 true 当且仅当集合中包含指定的项

func (String) HasAll

func (s String) HasAll(items ...string) bool

HasAll 如果并且仅如果所有项都包含在集合中,则返回 true

func (String) HasAny

func (s String) HasAny(items ...string) bool

HasAny 如果集合中包含任何项,则返回 true

func (String) Insert

func (s String) Insert(items ...string) String

Insert 向集合中添加数据

func (String) Intersection

func (s String) Intersection(s2 String) String

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

func (s String) IsSuperset(s2 String) bool

IsSuperset returns true if and only if s is a superset of s2.

func (String) Len

func (s String) Len() int

Len returns the size of the set.

func (String) List

func (s String) List() []string

List returns 内容作为已排序的字符串切片

func (String) PopAny

func (s String) PopAny() (string, bool)

PopAny returns 集合中一个单一元素

func (String) Union

func (s String) Union(s2 String) String

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

func (s String) UnsortedList() []string

UnsortedList return 内容以随机顺序排列的切片

Jump to

Keyboard shortcuts

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