我正在尝试找出一种方法来获取 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)避免将整个主体复制到内存中。
如果有人知道如何做到这一点,请添加您的答案。
- 1 回答
- 0 关注
- 179 浏览
添加回答
举报
0/150
提交
取消
