Recover
Recover from panics in deferred functions, re-panicking, and converting panics to errors at package boundaries.
The built-in recover stops a panic only when called directly by a deferred function in the same goroutine. It returns the panic value, or nil when there is no panic to recover.
This deferred function recovers the panic, so execution returns from main after the defer finishes.
package main
import "fmt"
func main() {
defer func() {
if value := recover(); value != nil {
fmt.Println("recovered:", value)
}
}()
panic("unexpected state")
}In production
Recover at a boundary such as an HTTP handler or a goroutine supervisor, where the code can log the failure and return an appropriate error. Do not silently discard the panic, and do not expect one goroutine to recover a panic from another.
Enjoyed this? Get more software craft delivered to your inbox.