For AI agents: the complete documentation index is available at https://massaman.dev/llms.txt, the full documentation bundle is available at https://massaman.dev/llms-full.txt, and this page is available as Markdown at https://massaman.dev/reference/control/orElse.md.

orElse

Pass an Err error to a recovery function returning another Result. An Ok passes through unchanged, without calling recovery. Inspired by Rust's Result::or_else.

Usage

orElse(result, recover)

import { err, ok, orElse, type Result } from 'massaman/control'

const primary: Result<string, TypeError> = err(new TypeError('Missing setting'))

const recovered = orElse(primary, (error) => ok(`Default: ${error.message}`))
// Ok('Default: Missing setting')

const failed = orElse(primary, () => err(new RangeError('No backup available')))
// Err<RangeError>; recovery can fail too.

orElse(ok('configured'), () => ok('fallback'))
// Original Ok('configured'); recovery is not called.

Parameters

resultResult<T, E>required

The result to recover. Its error is passed through without normalization.

recover(error: E) => Result<U, F>required

Called once on failure, or not at all on success. Must return a synchronous Result.

Returns

Result<T | U, F>. The original success or recovery Result is returned by reference. The original error type is replaced by the recovery error type, not automatically retained. To retain the original error, return err(error) from recovery.

Exceptions and async work

Unexpected recovery exceptions propagate; this helper is not a try/catch. Use attempt around throwing recovery work. Async callbacks are not accepted; use an explicit isOk guard when recovery needs to await a Promise.

See also