TaskEither<L, R>.tryCatch constructor

TaskEither<L, R>.tryCatch(
  1. Future<R> run(),
  2. L onError(
    1. Object error,
    2. StackTrace stackTrace
    )
)

Execute an async function (Future) and convert the result to Either:

  • If the execution is successful, returns a Right
  • If the execution fails (throw), then return a Left based on onError

Used to work with Future and exceptions using Either instead of try/catch.

/// From [Future] to [TaskEither]
Future<int> imperative(String str) async {
  try {
    return int.parse(str);
  } catch (e) {
    return -1; /// What does -1 means? 🤨
  }
}

TaskEither<String, int> functional(String str) {
  return TaskEither.tryCatch(
    () async => int.parse(str),
    /// Clear error 🪄
    (error, stackTrace) => "Parsing error: $error",
  );
}

Implementation

factory TaskEither.tryCatch(Future<R> Function() run,
        L Function(Object error, StackTrace stackTrace) onError) =>
    TaskEither<L, R>(() async {
      try {
        return Right<L, R>(await run());
      } catch (error, stack) {
        return Left<L, R>(onError(error, stack));
      }
    });