This is a type statement that is checked if the recovery error is of a specific type.
This type statement fails, resulting in a runtime error that continues to spin the stack, as if nothing had interrupted it.
This is useful if you are defining a local MyError type for the error and want to restore only that type.
You can see an example in Error Handling and Go "
Client code can test net.Error with a type statement, and then distinguish between transient network errors and permanent errors.
For example, a web crawler might:
- to sleep and try again when he encounters a temporary error
- and refuse otherwise.
if nerr, ok := err.(net.Error); ok && nerr.Temporary() { time.Sleep(1e9) continue } if err != nil { log.Fatal(err) }
If you have several types of errors that you want to recover, you can use the type switch in " Golang: return to deferral "
defer func() { if r := recover(); r != nil { fmt.Println("Recovered in f", r) // find out exactly what the error was and set err switch x := r.(type) { case string: err = errors.New(x) case error: err = x default: err = errors.New("Unknown panic") } // invalidate rep rep = nil // return the modified err and rep } }()
source share