为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 179 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号