api - How do I find out about possible error values of Go standard library functions? -
when calling go function returns error, wonder how deal non-nil error value. can abort, log it, or pass caller. or combination thereof. better if found out went wrong , reacted in more fine-grained manner.
thus, how can find out possible error values , meanings? example, want use http.newrequest
function. in docs. there, says there are possible error conditions not ones. how can find out these?
first off, if haven't read yet, recommend reading this blog article error handling in go, might clarify things you.
as finding out possible error values of go stdlib functions, if it's not explicitly documented, 1 option go read code. example, on http.newrequest function, can click on header, takes the source code. there can see right now, returns error in 1 case, when url parsing fails. exploring url.parse
function, you'll see may return url.error
, can check 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 parse error, may or may not want handle differently in 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 jimb's comment however, checking type of error in case not useful thing do. in 99.99% of cases need know creating request failed (err != nil
) , handle eventuality in appropriate way (logging, returning, etc).
Comments
Post a Comment