登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-05 08:00:38 362浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《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(以及使用 github.com/pkg/errorsgithub.com/friendsofgo/errorserrors.cause(err))的类型为 *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) 的解决方案,以避免将整个正文复制到内存中。

如果有人知道如何做到这一点,请添加您的答案。

今天关于《http超时时如何获取json.NewDecoder(body).Decode()的错误原因?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>