tryCatch<L, R> function
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));
}
}