douping5226 2015-01-03 20:05
浏览 35
已采纳

如何在Go中指定和处理特定错误?

I wrote this very basic parser that goes through Reddit JSON and am curious how I can specifically manage an error in Go.

For example I have this "Get" method for a link:

func Get(reddit string) ([]Item, error) {
    url := fmt.Sprintf("http://reddit.com/r/%s.json", reddit)
    resp, err := http.Get(url)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        return nil, err
    }
    /*
     * Other code here
    */
}

How can I handle, say, a 404 error from the StatusCode? I know I can test for the 404 error itself:

if resp.StatusCode == http.StatusNotfound {
    //do stuff here
}

But is there a way I can directly manage the resp.StatusCode != http.StatusOK without having to write a bunch of if statements? Is there a way I can use err in a switch statement?

  • 写回答

2条回答 默认 最新

  • douliao5467 2015-01-03 22:04
    关注

    Firstly note that http.Get doesn't return an error for an HTTP return which isn't 200. The Get did its job successfully even when the server gave it a 404 error. From the docs

    A non-2xx response doesn't cause an error.

    Therfore in your code, err will be nil when you call this which means it will return err=nil which probably isn't what you want.

    if resp.StatusCode != http.StatusOK {
        return nil, err
    }
    

    This should do what you want

    if resp.StatusCode != http.StatusOK {
        return nil, fmt.Errorf("HTTP Error %d: %s", resp.StatusCode, resp.Status)
    }
    

    Which will return an error for any kind of HTTP error, with a message as to what it was.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言数据结构实验单链表的删除
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline