我正在使用輔助函式來解碼 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() 無法識別錯誤型別?
uj5u.com熱心網友回復:
這有效:https ://go.dev/play/p/CWe9mVp7QOz 。
我能想到的唯一原因會導致你的代碼失敗,如果它真的失敗了,那就是使用的dto包與使用decodeJSONBody的dto包不同InternalTokenHandler.Post,因此兩種錯誤型別會不同。
請注意,即使是同一個包的不同版本也算作不同的包和在這些包中宣告的型別并不相同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/450156.html
標籤:走
