Either<L, R>.catchError constructor

Either<L, R>.catchError(
  1. ErrorMapper<L> errorMapper,
  2. R block()
)

Evaluates the specified block and wrap the result in a Right.

If an error is thrown, calling errorMapper with that error and wrap the result in a Left.

Example

Either<Object, int>.catchError((e, s) => e, () => throw Exception()); // Result: Left(Exception())
Either<Object, String>.catchError((e, s) => e, () => 'hoc081098');    // Result: Right('hoc081098')

Implementation

factory Either.catchError(ErrorMapper<L> errorMapper, R Function() block) {
  try {
    return Either.right(block());
  } catch (e, s) {
    return Either.left(errorMapper(e.throwIfFatal(), s));
  }
}