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

标签 go error-handling

我正在尝试找出一种在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/errorsgithub.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/

相关文章:

asp.net-mvc - 在 asp.net mvc 中处理错误和异常

javascript - 将额外变量传递给回调函数

mysql - 去和 mysql 和 cloneTLSConfig

http - 无需重置路由的最小 http 服务测试?

file - 如何获取自上次修改以来文件的添加内容

去fmt.Println显示错误包含

html - 使用Go访问DOM并获取数据

layout - 引入错误处理时如何保持代码布局可视化 'attractive'?

ios - 检查针对iOS运行xcodebuild(命令行)的错误

php - 基于异常的表单验证