asyncTry<R> function

FutureOr<R?> asyncTry<R>(
  1. FutureOr<R?> tryBlock(), {
  2. FutureOr<R?> then(
    1. R? r
    )?,
  3. Function? onError,
  4. FutureOr<void> onFinally()?,
})

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 after tryBlock completes successfully, receiving its result.
  • onError: A callback invoked if tryBlock or then throws an error, similar to Future.then's onError parameter.
  • onFinally: Always called after tryBlock, then, and onError, regardless of success or failure.

Returns:

  • Result of tryBlock passed to then, or an error handled by onError. 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);
  }
}