Sync<T extends Object> constructor

Sync<T extends Object>(
  1. @mustBeAnonymous @noFutures T noFutures(), {
  2. @noFutures TOnErrorCallback<T>? onError,
  3. @noFutures TVoidCallback? onFinalize,
})

Creates a Sync executing a synchronous function noFutures.

IMPORTANT:

Do not use any Futures in noFutures to ensure errors are be caught and propagated.

Implementation

factory Sync(
  @mustBeAnonymous @noFutures T Function() noFutures, {
  @noFutures TOnErrorCallback<T>? onError,
  @noFutures TVoidCallback? onFinalize,
}) {
  assert(!isSubtype<T, Future<Object>>(), '$T must never be a Future.');
  return Sync.result(() {
    try {
      return Ok(noFutures());
    } on Err catch (err) {
      return err.transfErr<T>();
    } catch (error, stackTrace) {
      try {
        if (onError == null) {
          rethrow;
        }
        return onError(error, stackTrace);
      } catch (error, stackTrace) {
        return Err<T>(error, stackTrace: stackTrace);
      }
    } finally {
      onFinalize?.call();
    }
  }());
}