Go - error.As() 无法转换类型
时间:2024-03-15
浏览: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知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
