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

如何查找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?

当调用返回错误的Go函数时,我想知道如何处理非nil错误值。 我可以中止,记录它或将其传递给呼叫者。 或其组合。 但是,如果我发现出了什么问题并以更细粒度的方式做出反应,那就更好了。 p>

因此,我如何找出可能的错误值及其含义? 例如,我要使用 http.NewRequest code>函数。 在文档中 查找。 在那里,它仅表示存在 em>个可能的错误条件,而不是哪个错误条件。 我如何找到这些? p> div>

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).