ExResilience.Fallback (ex_resilience v0.4.0)

Copy Markdown View Source

Stateless fallback layer for graceful degradation.

When the wrapped function returns an error, calls a fallback function instead. The fallback receives the error result and returns a replacement value.

Options

  • :name -- optional atom for telemetry metadata. Default :fallback.
  • :fallback -- required 1-arity function receiving the error result, returns the fallback value.
  • :only -- optional 1-arity predicate; fallback only triggers when this returns true. Default: matches {:error, _} and :error. Takes precedence over :error_classifier when both are provided.
  • :error_classifier -- module implementing ExResilience.ErrorClassifier. When provided (and :only is not), triggers fallback for results classified as :retriable or :failure. Ignored if :only is also set.

Examples

iex> ExResilience.Fallback.call(fn -> {:error, :down} end, fallback: fn _err -> {:ok, :cached} end)
{:ok, :cached}

iex> ExResilience.Fallback.call(fn -> {:ok, 42} end, fallback: fn _err -> {:ok, 0} end)
{:ok, 42}

Summary

Functions

Executes fun and applies the fallback if the result matches the error predicate.

Types

option()

@type option() ::
  {:name, atom()}
  | {:fallback, (term() -> term())}
  | {:only, (term() -> boolean())}
  | {:error_classifier, module()}

Functions

call(fun, opts)

@spec call((-> term()), [option()]) :: term()

Executes fun and applies the fallback if the result matches the error predicate.

The :fallback option is required and must be a 1-arity function that receives the error result.

Examples

iex> ExResilience.Fallback.call(
...>   fn -> {:error, :timeout} end,
...>   fallback: fn {:error, reason} -> {:ok, {:default, reason}} end
...> )
{:ok, {:default, :timeout}}

iex> ExResilience.Fallback.call(
...>   fn -> {:ok, :fast} end,
...>   fallback: fn _ -> {:ok, :slow} end
...> )
{:ok, :fast}