目录
- 背景
- 使用
- 参考
背景
使用原生go语言编程时,常常需要处理错误,然而golang中没有像java/python等其他语言的try-catch方式一样的方式来处理异常事件,只能通过函数返回值接收并处理错误。
在实践中,由于牛马的不熟练或随意处理错误(比如我),常常在各处打印错误日志,而实际翻找日志时很难定位错误根源。在中大型项目中,业务逻辑错综复杂,日志描述大量重复或者含糊不清,就很难排查问题了。
如果能根据在日志中看到错误的堆栈信息,是不是定位问题就变容易多了?!
https://github.com/pkg/errors 很符合我对错误处理的幻想,甚至比try-catch更方便。
使用
go get github.com/pkg/errors
package mainimport ("fmt""github.com/pkg/errors"
)func a(x int) error {if x == 2 {//return errors.Errorf("error because x is %d", x) // 会记录调用栈return errors.New("[a] error because x is 2") // 会记录调用栈}return nil
}func b(arr []int) error {for _, x := range arr {if err := a(x); err != nil {return errors.Wrap(err, "[b] failed to handle arr") // 包装,并且记录当前行的调用栈//return errors.WithMessage(err, "failed to handle arr") // 只包装,不记录当前行的调用栈}}return nil
}func c() error {err := b([]int{1, 2, 3, 4, 5})if err != nil {return errors.WithMessage(err, "[c] error") // 只包装,不记录当前行的调用栈}return nil
}func main() {err := c()if err != nil {fmt.Println("============================================")fmt.Printf("%v\n", err) // 打印错误信息fmt.Println("============================================")fmt.Printf("%v\n", errors.Cause(err)) // 打印错误根源信息fmt.Println("============================================")fmt.Printf("%+v\n", err) // 打印错误信息+堆栈信息fmt.Println("============================================")}
}
stdout:
============================================
[c] error: [b] failed to handle arr: [a] error because x is 2
============================================
[a] error because x is 2
============================================
[a] error because x is 2
main.a/Users/jinglong/Projects/my-go-projects/study/test_errors/main.go:12
main.b/Users/jinglong/Projects/my-go-projects/study/test_errors/main.go:19
main.c/Users/jinglong/Projects/my-go-projects/study/test_errors/main.go:28
main.main/Users/jinglong/Projects/my-go-projects/study/test_errors/main.go:36
runtime.main/Library/env/goenv/versions/1.21.13/src/runtime/proc.go:267
runtime.goexit/Library/env/goenv/versions/1.21.13/src/runtime/asm_arm64.s:1197
[b] failed to handle arr
main.b/Users/jinglong/Projects/my-go-projects/study/test_errors/main.go:20
main.c/Users/jinglong/Projects/my-go-projects/study/test_errors/main.go:28
main.main/Users/jinglong/Projects/my-go-projects/study/test_errors/main.go:36
runtime.main/Library/env/goenv/versions/1.21.13/src/runtime/proc.go:267
runtime.goexit/Library/env/goenv/versions/1.21.13/src/runtime/asm_arm64.s:1197
[c] error
============================================
参考
https://segmentfault.com/a/1190000045285259