asyncTry<R> function
Executes a tryBlock
with a try
, then
, catch
, and finally
flow.
tryBlock
: The operation to execute. If successful,then
is called.then
: A function called aftertryBlock
completes successfully, receiving its result.onError
: A callback invoked iftryBlock
orthen
throws an error, similar to Future.then'sonError
parameter.onFinally
: Always called aftertryBlock
,then
, andonError
, regardless of success or failure.
Returns:
- Result of
tryBlock
passed tothen
, or an error handled byonError
.onFinally
is 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);
}
}