Recover
Recover from panics in deferred functions, re-panicking, and converting panics to errors at package boundaries.
The built-in recover can stop a panic only when called directly by a function scheduled with defer, which runs a call when its function returns. It must run in the same goroutine, a function call started with go that can run while its caller continues. recover returns the value passed to panic, or nil if there is no panic.
This deferred function calls recover, so main can return after the deferred function finishes instead of the panic ending the program.
package main
import "fmt"
func main() {
defer func() {
if value := recover(); value != nil {
fmt.Println("recovered:", value)
}
}()
panic("unexpected state")
}In production
Recover only at a place where the program can report the failure or return a useful response. Log what happened and do not silently hide the panic. A function cannot recover a panic that happened in another goroutine.