DEV Community

Discussion on: Go 2 Draft: Error Handling

 
dean profile image
dean

It would look something like this:

In current Go with the handle construct would look something like this:

handle err {

    if notExist, ok := err.(*os.ErrNotExist); ok {
        // Do stuff with notExist
    } else if otherErr, ok := err.(*pack.OtherErr); ok {
        // Do stuff with otherErr
    }
}

// Or if your list is very long
handle err {
    switch err.(type) {
    case *os.ErrNotExist:
        // Code...
    case ...:
        // ...
    default:
        // ...
    }
}

Note that the notExist, ok := err.(*os.ErrNotExist) is how you typecast in Go. Also, a semicolon in an if statement means "just execute the left side normally and evaluate the right side as the condition", although any variables declared on the left side have block scope within the if statement.

Errors in Go are just an interface, so you just cast them to the error that you want to check.