tryCatch<L, R> function

Either<L, R> tryCatch<L, R>(
  1. Lazy<R> f,
  2. L onError(
    1. dynamic error,
    2. StackTrace stack
    )
)

Runs the given function, and the result is wrapped in a Right. If it raises an error, then the onError callback determines the Left value.

expect(
  tryCatch(() => 123, (err, stack) => 'fail'),
  right(123),
);
expect(
  tryCatch(() => throw 'error', (err, stack) => 'fail'),
  left('fail'),
);

Implementation

Either<L, R> tryCatch<L, R>(
  Lazy<R> f,
  L Function(dynamic error, StackTrace stack) onError,
) {
  try {
    return right(f());
  } catch (err, stack) {
    return left(onError(err, stack));
  }
}