2 回答

TA貢獻2080條經(jīng)驗 獲得超4個贊
type Error struct {
Message string
Code int
}
func (e *Error) Error() string {
return e.Message
}
func (e *Error) Is(tgt error) bool {
// This is never printed - this method never excutes for some reason
fmt.Println("compared!")
target, ok := tgt.(*Error)
if !ok{
return false
}
return e.Code == target.Code
}
您的 Error 結(jié)構(gòu)沒有正確實現(xiàn)方法,參數(shù)不Is應該是。errorError
看實際:
https://play.golang.org/p/vRQndE9ZRuH

TA貢獻1816條經(jīng)驗 獲得超6個贊
你可以使用這個:
package main
import (
"fmt"
)
type Error struct {
Message string
Code int
}
func (e *Error) Error() string {
return e.Message
}
func (e *Error) Is(target Error) bool {
// This is now printed
fmt.Println("compared!")
return e.Code == target.Code
}
var NotFoundError Error = Error{Code: 404, Message: "The page was not found"}
func NewError(errorType Error, message string) Error {
rc := errorType
rc.Message = message
return rc
}
func FetchImage() Error {
return NewError(NotFoundError, "That image is gone")
}
func main() {
err := FetchImage()
// Now it returns true
fmt.Println(err.Is(NotFoundError))
}
- 2 回答
- 0 關(guān)注
- 127 瀏覽
添加回答
舉報