2 回答
TA贡献2080条经验 获得超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 结构没有正确实现方法,参数不Is应该是。errorError
看实际:
https://play.golang.org/p/vRQndE9ZRuH
TA贡献1816条经验 获得超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 关注
- 148 浏览
添加回答
举报
