1. Usage
  2. Failure Handling
  3. Event Listeners

Fallbacks provide an alternative result or error for a failed execution.


Creating a Fallback is simple. You can create a fallback that provides a default result:

fallback := fallback.WithResult(defaultResult)

An alternative error:

fallback := fallback.WithError(ErrConnecting)

Or computes a different result or error:

fallback := fallback.WithFunc[any](func(e failsafe.Execution[any]) (any, error) {
  return ConnectToBackup(backupConfig)

Failure Handling

A Fallback can be configured to handle only certain results, errors, or conditions as failures:

  HandleErrors(ErrConnecting, ErrRetriesExceeded).

When using a Fallback in combination with another policy, it’s common to configure both to handle the same failures. It’s also common for Fallback to handle errors that may be returned by inner policies in a composition, such as ErrRetriesExceeded, ErrCircuitBreakerOpen, or ErrTimeoutExceeded.

Event Listeners

In addition to the standard policy event listeners, a Fallback can notify you with an ExecutionDoneEvent when it handles a failure:

builder.OnFallbackExecuted(func(e failsafe.ExecutionDoneEvent[any]) {
  logger.Info("Fallback executed", "result", e.Result)