It's really a science to handle errors gracefully!

新亮
中文

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

阅读 1.7k

新亮笔记
技术的深度和广度只能靠自己努力去发掘,谁也不能替你学习,在这里希望你能有所收获。

日拱一卒

2.9k 声望
1.2k 粉丝
0 条评论

日拱一卒

2.9k 声望
1.2k 粉丝
文章目录
宣传栏