覆盖错误。Is() 不适用于自定义错误

我正在尝试在 Go 中创建一个自定义错误,以便我可以使用自定义消息创建该错误的新实例,然后处理该特定类型的错误。但是,当我尝试这样做时,我的覆盖errors.Is()不会被执行。这是我的代码:


package main


import (

        "fmt"

        "errors"

)


type Error struct {

        Message string

        Code int

}


func (e *Error) Error() string {

        return e.Message

}


func (e Error) Is(target Error) bool {

        // This is never printed - this method never excutes for some reason

        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()


        // Returns false

        fmt.Println(errors.Is(err, NotFoundError))

}

在这种情况下,调用errors.Is()返回 false。然而,即使我提供了自己的 Is() 函数,该函数根本没有被调用。也就是说,"compared!"永远不会打印字符串。


为什么我的 Is() 函数没有按预期工作?


慕哥6287543
浏览 149回答 2
2回答

犯罪嫌疑人X

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

潇湘沐

你可以使用这个:package mainimport (        "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))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go