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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。