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