亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go - errors.As() 無法識別類型

Go - errors.As() 無法識別類型

Go
慕虎7371278 2022-11-23 20:20:11
我正在使用輔助函數來解碼 JSON。它返回一個自定義錯誤類型,其中填充了無法解析 JSON 的原因和我應該返回的 HTTP 代碼。package dtotype MalformedRequestError struct {    Status  int    Message string}func (mr *MalformedRequestError) Error() string {    return mr.Message}解碼主體時我做的第一件事就是檢查客戶端是否正確設置了 Content-Type 標頭。package webhandlersfunc 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 webhandlersfunc (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() 無法識別錯誤類型?
查看完整描述

1 回答

?
牛魔王的故事

TA貢獻1830條經驗 獲得超3個贊

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

我能想到的唯一會導致您的代碼失敗的原因(如果它真的失敗了)是所dto使用的包decodeJSONBody與所dto使用的包不同InternalTokenHandler.Post,因此這兩種錯誤類型會不同。

請注意,即使是同一包的不同版本也算作不同的包,其中聲明的類型也不相同。


查看完整回答
反對 回復 2022-11-23
  • 1 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號