doucigua0449 2016-02-05 21:21
浏览 16
已采纳

如何查找Go标准库函数的可能错误值?

When calling a Go function that returns an error, I wonder how to deal with a non-nil error value. I can just abort, log it, or pass it to the caller. Or a combination thereof. But it would be better if I found out what went wrong and reacted in a more fine-grained manner.

Thus, how can I find out about possible error values and their meanings? For example, I want to use the http.NewRequest function. Look it up in the docs. There, it only says that there are possible error conditions but not which ones. How can I find out about these?

  • 写回答

1条回答 默认 最新

  • dongyingla8668 2016-02-06 03:58
    关注

    First off, if you haven't read it yet, I recommend reading this blog article about error handling in Go, it might clarify some things for you.

    As for finding out the possible error values of Go stdlib functions, if it's not explicitly documented, one option is to go read the code. For example, on the http.NewRequest function, you can click on the header, which takes you to the source code. There you can see that right now, it only returns an error in one case, when the URL parsing fails. Exploring the url.Parse function, you'll see that it may return url.Error, which you can check for with a type assertion:

    package main
    
    import (
        "log"
        "net/http"
        "net/url"
    )
    
    func main() {
        r, err := http.NewRequest("GET", "http://[fe80::%31%25en0]:8080/", nil)
        if perr, ok := err.(*url.Error); ok && perr != nil {
            log.Fatal("Parse error, check URL formatting: ", perr)
        } else if err != nil {
            log.Fatal("Error creating HTTP request")
        }
    
        // ... success case
        log.Println(r)
    }
    

    Running this gives you the parse error, which you may or may not want to handle differently in your application:

    2009/11/10 23:00:00 Parse error, check URL formatting: parse http://[fe80::%31%25en0]:8080/: percent-encoded characters in host
    

    I agree with JimB's comment however, specifically checking the type of error in this case is probably not a useful thing to do. In 99.99% of cases all you need to know is that creating the request failed (err != nil) and handle that eventuality in an appropriate way (logging, returning, etc).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因