'How to `catch` specific errors

For example, I am using one Go standard library function as:

func Dial(network, address string) (*Client, error)

This function may return errors, and I just care about errors which report "connection lost" or "connection refused", then do some code to fix these.
It seems like:

client, err := rpc.Dial("tcp", ":1234")  
if err == KindOf(ConnectionRefused) {
  // do something
}

What's more, how to get all the errors a specific standard library function may return?



Solution 1:[1]

You can now use the errors.Is() function to compare some standard errors:

client, err := net.Dial("tcp", ":1234")
if errors.Is(err, net.ErrClosed) {
    fmt.Println("connection has been closed.")
}

A common file opening scenario:

file, err := os.Open("non-existing");
if err != nil {
    if errors.Is(err, fs.ErrNotExist) {
        fmt.Println("file does not exist")
    } else {
        fmt.Println(err)
    }
}

UPDATE
You can also use errors.As() if you'd like to check the error type:

client, err := net.Dial("tcp", ":1234")
var errC = net.ErrClosed
if errors.As(err, &errC) {
    fmt.Printf("connection has been closed: %s", errC)
}
client.Close()

A more detailed explanation can be found in the Go Blog.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1