1 回答

TA貢獻1752條經(jīng)驗 獲得超4個贊
讓我們將這個例子提煉成它的本質(zhì)。
package customerror
import (
"errors"
)
type CustomError struct {
Aux string
Err error
}
func (cE *CustomError) Error() string { /*...*/ }
func (err *CustomError) Unwrap() error { return err.Err }
func NewFailedToError(aux string, err error) error {
return &CustomError{ Aux: aux, Err: err }
}
var FailedToWriteToFile = NewFailedToError("write to file", nil)
我們現(xiàn)在可以進入要點中的問題:
// Some function just for demonstration.
func WriteToFile() error {
// Something caused some error..
errSome := errors.New("Failed to open file")
// How can I set the `err` value of `FailedToWriteToFile` to `errSome`
// without setting that for all `FailedToWriteToFile` instances (pointer)?
// while still making it of `FailedToWriteToFile` type (errors.Is(errSome, FailedToWriteToFil))?
return FailedToWriteToFile
}
讓我們將這個問題重新構(gòu)建為如何用新消息進行構(gòu)建。errSome
errors.Is(errSome, FailedToWriteToFil)
我們可以檢查錯誤的文檔。是
:
報告錯誤鏈中的任何錯誤是否與目標(biāo)匹配。
該鏈由錯誤本身組成,后跟通過反復(fù)調(diào)用 Unwrap 獲得的錯誤序列。
如果錯誤等于目標(biāo),或者如果它實現(xiàn)了 Is(錯誤) bool 的方法,使得 Is(target) 返回 true,則該錯誤被視為與該目標(biāo)匹配。
錯誤類型可能提供 Is 方法,以便將其視為與現(xiàn)有錯誤等效。例如,如果“我的錯誤”定義
func (m MyError) Is(目標(biāo)錯誤) bool { 返回目標(biāo) == fs.錯誤存在 }
然后 Is(MyError{}, fs.錯誤存在) 返回真值。有關(guān)標(biāo)準(zhǔn)庫中的示例,請參閱 syscall.Errno.Is。
這給了我們兩條道路。其中一條路徑是放在展開鏈上。如果我們使用 Err 字段指向 ,則自定義錯誤具有足夠的字段,例如FailedToWriteToFile
FailedToWriteToFile
&CustomError{Aux: "Failed to open file", Err: FailedToWriteToFile}
解開包裝()是 == 到 。FWIW AUX 可能是類型錯誤的字段,如果您嘗試捕獲來自其他源的錯誤值。只要解開包裝()鏈最終導(dǎo)致。FailedToWriteToFile
FailedToWriteToFile
另一條路徑是在 上定義謂詞。有很多可能的謂詞可供選擇。一個簡單的問題是,所有 *自定義錯誤都被視為等效的。這將是:Is
CustomError
func (e *CustomError) Is(target error) bool { _, ok := target.(*CustomError) return ok }
- 1 回答
- 0 關(guān)注
- 103 瀏覽
添加回答
舉報