Fallback

  1. Usage
  2. Failure Handling
  3. Event Listeners

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

Usage

There are a few different options for creating a Fallback. You can provide an alternative result:

fallback := fallback.WithResult(defaultResult)

An alternative error:

fallback := fallback.WithError(ErrConnecting)

Or compute a different result or error:

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

Using a Fallback is simple:

connection, err := failsafe.Get(Connect, fallback)

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