douzhi7070 2016-08-24 10:06
浏览 48
已采纳

解释Golang错误代码

So most examples of go error handling I see just pass any errors back up the stack. At some point these need interpreting and this is what I am trying to do. Here's a snippet of my attempt:

    resp, err := http.Get(string(url))
    defer out_count.Dec()

    if err != nil {

           switch err {
            case http.ErrBodyReadAfterClose:
                    fmt.Println("Read after close error")
            case http.ErrMissingFile:
                    fmt.Println("Missing File")
            {some more cases here}
            case io.EOF:
                    fmt.Println("EOF error found")
            default:
                    fmt.Printf("Error type is %T
", err)
                    panic(err)
            }
            return

This isn't working though for my current case(edited to remove url}:

ERROR: Failed to crawl "http://{removed URL}"
Error type is *url.Error
panic: Get http://{removed url}: EOF

goroutine 658 [running]:
runtime.panic(0x201868, 0x106352c0)
        /usr/lib/go/src/pkg/runtime/panic.c:279 +0x1a0
github.com/cbehopkins/grab/grab.crawl(0x10606210, 0x27, 0x105184b0, 0x105184e0, 0x10500460)

I can't figure out a way to get the switch statement to catch this error since the text of the error changes every time and has no explicit value I can catch against. (as the URL changes all the time). Now maybe I could do some sort of regex match in the case statement or sub-slice the error string, but that feels like a very bad way to solve this problem.

Any suggestions? There must be an idiomatic way to catch errors such as this surely?

  • 写回答

2条回答 默认 最新

  • duanjuda5789 2016-08-24 10:29
    关注

    The simplest way would be to have package level error values in your code:

    var URLFetchError = errors.New("Cannot fetch URL")
    
    url := "http://www.google.com"
    res, err := http.Get(url)
    if err != nil {
        return URLFetchError
    }
    

    The switch then becomes:

    switch err {
    case http.ErrBodyReadAfterClose:
        fmt.Println("Read after close error")
    case URLFetchError:
        fmt.Println("Error fetching URL")
    

    If you want to pass more information with the error, you can create your own custom errors:

    type MyError struct {
        URL string
    }
    
    func (e MyError) Error() string {
        return fmt.Sprintf("Error getting: %v", e.URL)
    }
    

    Then, you can create this error whenever required. For example:

    url := "http://www.google.com"
    res, err := http.Get(url)
    if err != nil {
        return MyError{url}
    }
    

    Finally, in your error checking method, you can use type switches instead of simple switches to get the error:

    switch err.(type) {
    case MyError:
        fmt.Println("Error:", err)
    default:
        fmt.Println("No Error")
    }
    

    In your case, since you have a mix of regular error, you can include this check in a nested switch:

    switch err {
    case http.ErrBodyReadAfterClose:
        fmt.Println("Read after close error")
    case http.ErrMissingFile:
        fmt.Println("Missing File")
    case io.EOF:
        fmt.Println("EOF error found")
    default: // check for custom errors
        switch err.(type) {
        case MyError:
            fmt.Println("custom error:", err)
        default:
            panic(err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用三极管设计—个共射极放大电路
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示