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

Taught in

References