登录
首页 >  Golang >  Go问答

Go - error.As() 无法转换类型

来源:stackoverflow

时间:2024-03-15 19:18:29 277浏览 收藏

Go 语言中,`errors.As()` 用于检查错误是否可以转换为特定类型。当辅助函数 `decodeJSONBody` 返回自定义错误 `*dto.malformedrequesterror` 时,代码尝试使用 `errors.As()` 将错误转换为该类型,但失败了。这可能是由于 `decodeJSONBody` 使用的 `dto` 包与代码中使用的 `dto` 包不同,导致错误类型不同。

问题内容

我正在使用辅助函数来解码 json。它返回一个自定义错误类型,其中填充了无法解析 json 的原因以及我应该返回的 http 代码。

package dto

type malformedrequesterror struct {
    status  int
    message string
}

func (mr *malformedrequesterror) error() string {
    return mr.message
}

解码正文时我要做的第一件事就是检查客户端是否正确设置了 content-type 标头。

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() 来检查该函数是否返回我的自定义错误,但它不起作用。

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 块并返回通用服务器 500 错误。

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


正确答案


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

我能想到的导致代码失败的唯一原因(如果确实失败)是 decodeJSONBody 使用的 dto 包与 dto 使用的 dto 包不同,因此出现两个错误类型会有所不同。

请注意,即使同一包的不同版本也算作不同的包,并且这些包中声明的类型不相同相同

好了,本文到此结束,带大家了解了《Go - error.As() 无法转换类型》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>