runCatching<R> function
Calls the specified function block
and returns
your value encapsulated in the Result if invocation is successful,
catches any error
that is thrown from the block
function execution,
then test
is called with the error value, if test
is true
,
the error
and the StackTrace are encapsulating it as a failure
in Result, otherwise, if test
is false, then the error
is rethrow.
If test
is omitted, it defaults to a function that always returns true
.
It's very similar with Future.catchError.
Note, that this function rethrows
any error
thrown by test
function.
Implementation
Result<R> runCatching<R>(
Block<R> block, {
bool Function(Object error)? test,
}) {
try {
return Result.success(block());
} catch (error, stackTrace) {
if (test?.call(error) ?? true) {
return Result.failure(error, stackTrace);
}
rethrow;
}
}