1

errors

Everyone must have used this. The errors standard library is relatively simple and cannot be traced back to the stack. It is not very friendly to the upper-level caller when the error occurs, and the detailed information of the wrong call chain cannot be obtained.

// 不带堆栈
err := errors.New("error msg")
fmt.Printf("%+v\n", err)

// 输出
error msg

pkg/errors

github.com/pkg/errors supports stack information, and you can get detailed information about the wrong call chain.

normal

// 带堆栈
err := errors.New("error msg")
fmt.Printf("%+v\n", err)

// 输出
error msg
main.main
        /Users/xinliang/go/project/demo/err/err.go:14
runtime.main
        /usr/local/go/src/runtime/proc.go:225
runtime.goexit
        /usr/local/go/src/runtime/asm_amd64.s:1371

With stack, package description

err := errors.Wrap(err error, message string)

或

err := errors.Wrapf(err error, format string, args ...interface{})

With stack, without packaging description

err := errors.WithStack(err error)

Without stack, package description

err := errors.WithMessage(err error, message string)

或 

err := errors.WithMessagef(err error, format string, args ...interface{})

Thinking

Think about it, everyone, what problems will we encounter when pkg/errors

Will encounter the problem of duplicate stacks!

For example, if the call link of a method is relatively long, this will happen, for example:

func main() {
    err := func1()
    fmt.Printf("%+v\n", errors.Wrapf(err, "func1 error occurred"))
}

func func1() error {
    err := func2()
    return errors.Wrapf(err, "func2 error occurred")
}

func func2() error {
    err := errors.New("error msg")
    return err
}

Think about it, what will print?

Did you find that the printed stack information is duplicated?

How to solve this problem? Come and discuss with my planet, https://t.zsxq.com/iIUVVnA


程序员新亮
2.9k 声望1.2k 粉丝

GitHub 9K+ Star,其中适合 Go 新手的开箱即用项目 go-gin-api 5.2K Star:[链接],联系我:wx-xinliang