Overview
Takes anErr value and maps it to a Result<T, SomeNewType>. This is the error-handling counterpart to andThen, useful for error recovery and fallback logic.
Signature
Parameters
(e: E) => Result<U, A>
required
A function that takes the Err value and returns a new Result. This function is only called if the current Result is Err.
Returns
Returns a newResult<T | U, A> where:
- If the original Result is
Ok(value), returnsOk(value)without callingf - If the original Result is
Err(error), returns the result off(error) - The success type becomes a union of both possible success types
Examples
Basic Error Recovery
Error Recovery with Fallback
Multi-Level Fallbacks
Converting Errors to Success
Selective Error Recovery
Chaining Recovery Strategies
Real-World Example
Implementation Details
From the source code (result.ts:470-472):Ok (result.ts:366-368):
Notes
orElseoperates on the error path, whileandThenoperates on the success path- Useful for implementing retry logic, fallbacks, and graceful degradation
- The success type becomes a union of both possible success types
- Can convert errors to successes for complete error recovery
- For operations on Ok values, use andThen()
Related
- Result.andThen() - Chain operations on the success path
- Result.mapErr() - Transform errors without changing to Ok
- Result.match() - Handle both Ok and Err cases