Recovering from panics
An unhandled panic will terminate the program. Often, this is the only correct course of action. However, there are cases where you want to fail whatever caused the error, log it, and continue. For example, a server handling many requests concurrently does not terminate just because one of the requests panicked. This recipe shows how you can recover from a panic.
How to do it...
Use a recover
statement in a defer
function:
func main() { defer func() { if r:=recover(); r != nil { // deal with the panic } }() ... }
How it works...
When a program panics, the panicking function will return after all deferred blocks are executed. The stack of that goroutine will unroll one function after the other, cleaning up by running their deferred
statements, until the beginning of the goroutine is reached, or one of the...