Fallback

  1. Usage
  2. Failure Handling
  3. Event Listeners

Fallbacks handle failed executions by providing an alternative result or error.

Usage

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:

builder.
  HandleErrors(ErrConnecting, retrypolicy.ErrExceeded).
  HandleResult(nil)

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 retrypolicy.ErrExceeded, circuitbreaker.ErrOpen, or timeout.ErrExceeded.

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)
})