地址: https://github.com/morrisxyang/errors
如果覺得有用歡迎 Star 和 PR, 有問題請直接提issue
errors
簡單的支持錯誤堆疊, 錯誤碼, 錯誤鏈的工具庫:
-
支持攜帶堆疊, 嵌套構造錯誤鏈
-
支持攜帶錯誤碼, 方便介面回傳
-
支持自定義堆疊列印深度和錯誤鏈列印格式
-
使用 CallersFrames 替代 FuncForPC 生成堆疊, 避免特殊情況
line number錯誤
等問題, 詳見runtime: strongly encourage using CallersFrames over FuncForPC with Callers result -
簡化堆疊資訊, 一條鏈路多次
Wrap
操作只保留最深層堆疊, 只列印一次
安裝和檔案
安裝使用 go get github.com/morrisxyang/errors
檔案地址是 https://pkg.go.dev/github.com/morrisxyang/errors
快速開始
構造錯誤鏈
func a() error {
err := b()
err = Wrap(err, "a failed reason")
return err
}
func b() error {
err := c()
err = Wrap(err, "b failed reason")
return err
}
func c() error {
_, err := os.Open("test")
if err != nil {
return WrapWithCode(err, 123, "c failed reason")
}
return nil
}
列印錯誤資訊, %+v
會列印堆疊, %v
只列印錯誤資訊
a failed reason
Caused by: b failed reason
Caused by: 123, c failed reason
Caused by: open test: no such file or directory
github.com/morrisxyang/errors.c
/Users/morrisyang/Nutstore Files/go-proj/githuberrors/errors_test.go:94
github.com/morrisxyang/errors.b
/Users/morrisyang/Nutstore Files/go-proj/githuberrors/errors_test.go:86
github.com/morrisxyang/errors.a
/Users/morrisyang/Nutstore Files/go-proj/githuberrors/errors_test.go:80
....堆疊資訊省略
核心方法
錯誤封裝
- func New(msg string) error
- func Newf(format string, args ...interface{}) error
- func NewWithCode(code int, msg string) error
- func NewWithCodef(code int, format string, args ...interface{}) error
- func Wrap(e error, msg string) error
- func Wrapf(e error, format string, args ...interface{}) error
- func WrapWithCode(e error, code int, msg string) error
- func WrapWithCodef(e error, code int, format string, args ...interface{}) error
錯誤決議
- func Code(e error) int
- func EffectiveCode(e error) int
- func Msg(e error) string
- func As(err error, target interface{}) bool
- func Is(err, target error) bool
- func Cause(e error) error
- func Unwrap(err error) error
配置
-
type Config
-
- func GetCfg() *Config
-
func ResetCfg()
-
func SetCfg(c *Config)
FAQ
-
多次 Wrap 錯誤會攜帶多次堆疊嗎?
可在呼叫鏈路上多次Wrap, 添加說明資訊, 但只有最深層的Wrap操作會設定堆疊, 繼續
Wrap
,return err
等操作不會影響堆疊資訊 -
在鏈路中某個錯誤設定了合適的錯誤碼, 然后繼續Wrap時沒有設定, 如何獲取?
建議在合適的清晰的時機設定有效的錯誤碼, 可以使用
EffectiveCode
獲取鏈路中外層第一個有效的非0錯誤碼, 由于系統呼叫等情況, 同一鏈路中可能有多個錯誤攜帶錯誤碼, 此時默認外層的錯誤碼應該對外暴露, 屏蔽了內層的詳細資訊.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/556912.html
標籤:其他
下一篇:返回列表