我正在尝试找出一种在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)
最佳答案
好的,所以我最终将响应主体读入[]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)
的解决方案,以避免将整个主体复制到内存中。如果有人知道该怎么做,请添加您的答案。
关于go - 发生http超时时,如何获取json.NewDecoder(body).Decode()的错误原因?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58731147/