1 回答

TA貢獻1816條經驗 獲得超4個贊
這是預期的工作,這不違反文檔。多個錯誤可能包含在單個error值中,并且由于調用Unwrap()返回單個錯誤,顯然沒有得到您期望的內容并不意味著沒有包含預期的錯誤。
該errors軟件包來自標準庫。它沒有errors.Wrap()功能。您使用的是 from github.com/pkg/errors.Wrap(),它在引擎蓋下進行“雙重包裝”。
首先它用給定的錯誤消息包裝錯誤,然后再次包裝以保留堆棧信息:
// Wrap returns an error annotating err with a stack trace
// at the point Wrap is called, and the supplied message.
// If err is nil, Wrap returns nil.
func Wrap(err error, message string) error {
if err == nil {
return nil
}
err = &withMessage{
cause: err,
msg: message,
}
return &withStack{
err,
callers(),
}
}
當您調用時Unwrap(),將返回來自第二次包裝的錯誤(這不是原始錯誤,而是包裝原始錯誤的包裝錯誤),Unwrap()再次調用將返回原始錯誤。
fmt.Println("Double unwrap:",
errors.Unwrap(errors.Unwrap(err2wrp)) == err1)
這就是為什么你應該使用errors.Is()來避免這種“怪癖”:
fmt.Println("Proper use:", errors.Is(err2wrp, err1))
在Go Playground上試試這些。
請注意,以上報告true
是您調用github.com/pkg/errors.Is()
還是標準庫的errors.Is()
.
- 1 回答
- 0 關注
- 119 瀏覽
添加回答
舉報