asyncTry<R> function
Executes a tryBlock with a try, then, catch, and finally flow.
tryBlock: The operation to execute. If successful,thenis called.then: A function called aftertryBlockcompletes successfully, receiving its result.onError: A callback invoked iftryBlockorthenthrows an error, similar to Future.then'sonErrorparameter.onFinally: Always called aftertryBlock,then, andonError, regardless of success or failure.
Returns:
- Result of
tryBlockpassed tothen, or an error handled byonError.onFinallyis always executed.
Example:
final result = await asyncTry<String>(
() => fetchData(),
then: (r) => processData(r),
onError: (error) => handleError(error),
onFinally: () => cleanUp(),
);
Implementation
FutureOr<R?> asyncTry<R>(FutureOr<R?> Function() tryBlock,
{FutureOr<R?> Function(R? r)? then,
Function? onError,
FutureOr<void> Function()? onFinally}) {
var thenFunction = then != null ? _ThenFunction<R>(then) : null;
var errorFunction = onError != null ? _ErrorFunction<R>(onError) : null;
var finallyFunction =
onFinally != null ? _FinallyFunction<R>(onFinally) : null;
try {
var ret = tryBlock();
if (ret is Future<R?>) {
return _returnFuture<R>(
ret, thenFunction, errorFunction, finallyFunction);
} else {
return _returnValue<R>(ret, thenFunction, errorFunction, finallyFunction);
}
} catch (e, s) {
return _completeError(e, s, errorFunction, finallyFunction);
}
}