catchResult<T, E> function

Result<T, E> catchResult<T, E>(
  1. Result<T, E> fn()
)

Executes the given function, returning the returned Result value.

If a ResultError is thrown during the execution of the given function, which occurs when an Err() value is unwrapped, the Err() that was unwrapped will be returned.

This effectively allows safely unwrapping Result values within the given function, propagating Err() to the returned value in the same way that the ? operator does in Rust. The simplest way to do this is to wrap your function body inside this function like so:

// The equivalent (non-idiomatic) Rust return in divideByTwo() would be:
// return Ok(value? / 2);

Result<int, String> divideByTwo(Result<int, String> value) => catchResult(() {
  return Ok(value.unwrap() ~/ 2);
});

Result<int, String> foo = Ok(42);
Result<int, String> bar = Err('There was an error!');

Result<int, String> result1 = divideByTwo(foo); // Ok(21)
Result<int, String> result2 = divideByTwo(bar); // Err('There was an error!')

Note that any other type of thrown error/exception other than ResultError will be rethrown. Additionally, The propagated Err() type will be repackaged to match the T of the expected return type of this function, and if the E value type of the propagated Err() does not match the expected E value type of this function, a ResultError will be thrown.

See also: Result.call()

Implementation

Result<T, E> catchResult<T, E>(Result<T, E> Function() fn) {
	try { return fn(); }
	catch (error) { return _handleResultError(error); }
}