http超时时如何获取json.NewDecoder(body).Decode()的错误原因?

我正在尝试找出一种方法来获取 JSON 解码时的错误原因http.Response.Body


if 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)


慕工程0101907
浏览 180回答 1
1回答

慕妹3242003

好的,所以我最终将响应正文读入 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 LResponseif err := json.Unmarshal(bb, &lResp); err != nil {    return nil, errors.Wrap(err, "failed to unmarshal LResponse")}我仍在寻找一种解决方案来json.NewDecoder(resp.Body).Decode(&str)避免将整个主体复制到内存中。如果有人知道如何做到这一点,请添加您的答案。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go