recover
The built-in Go function that, called inside a deferred function, stops a panic and returns the value it was raised with.
In more detail
recover only works in a deferred call; elsewhere it returns nil. Use it at a deliberate boundary, such as a worker supervisor, to turn a panic into an error and keep the rest of the program alive. It does not repair corrupted state, so log the failure and do not carry on as if nothing happened.
Example
defer func() {
if value := recover(); value != nil {
err = fmt.Errorf("worker panic: %v", value)
}
}()Related terms
- panic — A Go run-time failure that stops normal execution, runs deferred functions and, unless recovered, crashes the program with a stack trace.
- defer — A Go statement that schedules a function call to run when the surrounding function returns, used for cleanup such as closing a file.
- invariant — A rule that must always hold for an object or system, such as a count never being negative.
Taught in
- Panics and Recover — Concurrent Systems Programming with Go