Go - errors.As() 无法识别类型

Go - errors.As() not recognising type

我正在使用辅助函数来解码 JSON。它 return 是一种自定义错误类型,填充了无法解析 JSON 的原因和我应该 return.

的 HTTP 代码
package dto

type MalformedRequestError struct {
    Status  int
    Message string
}

func (mr *MalformedRequestError) Error() string {
    return mr.Message
}

我在解码 body 时做的第一件事就是检查客户端是否正确设置了 Content-Type header.

package webhandlers

func decodeJSONBody(w http.ResponseWriter, r *http.Request, dst interface{}) error {
    if r.Header.Get("Content-Type") != "" {
        value, _ := header.ParseValueAndParams(r.Header, "Content-Type")
        if value != "application/json" {
            Message := "Content-Type header is not application/json"
            return &dto.MalformedRequestError{Status: http.StatusUnsupportedMediaType, Message: Message}
        }
    }
    ... etc ...

我尝试使用 errors.As() 检查该函数是否 return 我的自定义错误,但它不起作用。

package webhandlers

func (i *InternalTokenHandler) Post(w http.ResponseWriter, r *http.Request) {
    type postRequest struct {
        Google_id_token string
    }
    // parse request data
    var parsedRequest postRequest
    err := decodeJSONBody(w, r, &parsedRequest)
    if err != nil {
        // outputs *dto.MalformedRequestError
        fmt.Println(fmt.Sprintf("%T", err))
        var mr *dto.MalformedRequestError
        if errors.As(err, &mr) {
            http.Error(w, mr.Message, mr.Status)
        } else {
            log.Println(err)
            http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
        }
        return
    }
    .... more code ...

我检查过错误的类型是 *dto.MalformedRequestError,但我的代码总是到达 else 块并且 return 出现通用服务器 500 错误。

我错过了什么 - 为什么 errors.As() 无法识别错误类型?

这有效:https://go.dev/play/p/CWe9mVp7QOz

我能想到的导致代码失败的唯一原因是 decodeJSONBody 使用的 dto 包与 dto 包被 InternalTokenHandler.Post 使用,因此两种错误类型会有所不同。

请注意,即使是同一软件包的不同版本也算作不同的软件包,其中声明的类型并不相同