Golang restore return value syntax

I'm trying to figure out how to recover from a panic situation. Usually something like this will do:

if r := recover(); r != nil { fmt.Println("Recovered in f", r) } 

I can understand a lot. But I saw a code snippet as shown below:

  if r, ok := recover().(error); ok { fmt.Println("Recovered in f", r) } 

What does this part do. (error)?

+5
source share
1 answer

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 } }() 
+11
source

Source: https://habr.com/ru/post/1201706/


All Articles