How to "catch" a specific error in golang
For example, I am using one golang standard library function as:
func Dial(network, address string) (*Client, error)
This function can return errors, and I just take care of errors that say "lost connection" or "refused connection" and then run some codes to fix them.
It seems that:
client, err := rpc.Dial("tcp", ":1234")
if err == KindOf(ConnectionRefused) {
// do something
}
What else, how to get all the errors a specific standard library function can return?
source to share
There is no standard way to do this.
The most obvious way, which should only be used if no other method exists, is to compare the error string with what you expect:
if err.Error() == "connection lost" { ... }
Or perhaps more robust in some situations:
if strings.HasSuffix(err.Error(), ": connection lost") { ... }
However, many libraries return certain types of errors, which greatly simplifies the process.
In your case, the different types of errors exported by the package net
are important : AddrError , DNSConfigError , DNSError , Error , etc.
You probably like net.Error the most , which is used for network errors. So you can check:
if _, ok := err.(net.Error); ok {
// You know it a net.Error instance
if err.Error() == "connection lost" { ... }
}
What else, how to get all the errors a specific standard library function can return?
The only reliable way to do this is to read the source for the library. Before going to this extreme, the first step is to just read the godoc, as in the case of the package net
, the errors are pretty well documented.
source to share