TaskEither<L, R>.tryCatch constructor
TaskEither<L, R>.tryCatch (
- Future<
R> run(), - L onError(
- Object error,
- 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 ononError
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));
}
});