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

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

http超時時如何獲取json.NewDecoder(body).Decode()的錯誤原因?

http超時時如何獲取json.NewDecoder(body).Decode()的錯誤原因?

Go
慕工程0101907 2023-07-31 17:16:34
我正在嘗試找出一種方法來獲取 JSON 解碼時的錯誤原因http.Response.Bodyif err := json.NewDecoder(resp.Body).Decode(&lResp); err != nil {? ? // Get the cause of err}的類型err(并errors.Cause(err)使用github.com/pkg/errors或github.com/friendsofgo/errors)是*errors.errorString。所以我現在能做的與檢查錯誤類型完全相反,即:if strings.HasSuffix(cause.Error(), "(Client.Timeout exceeded while reading body)") {? ? //...}我可以嘗試使用ioutil.ReadAll(),然后*http.httpError當超時發生時我會得到一個錯誤。主要原因是我不想獲取錯誤中部分讀取的 JSON 結構 - 僅獲取錯誤的原因,并且以當前的方式,它正在完成(返回的錯誤)我得到:main.ListingResponse.DataSources: struct CustomType{ /* partially read JSON struct ... */ }.net/http: request canceled (Client.Timeout exceeded while reading body)
查看完整描述

1 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

好的,所以我最終將響應正文讀入 a 中[]byte,然后使用json.Unmarshal()


bb, err := ioutil.ReadAll(resp.Body)

if err != nil {

    var netError net.Error

    if errors.As(err, &netError) {

        log.Printf("netError %v", netError)

        // handle net.Error...

        return nil, netError

    }

    // handle general errors...

    return nil, netError

}


var lResp LResponse

if err := json.Unmarshal(bb, &lResp); err != nil {

    return nil, errors.Wrap(err, "failed to unmarshal LResponse")

}

我仍在尋找一種解決方案來json.NewDecoder(resp.Body).Decode(&str)避免將整個主體復制到內存中。


如果有人知道如何做到這一點,請添加您的答案。


查看完整回答
反對 回復 2023-07-31
  • 1 回答
  • 0 關注
  • 133 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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