Sync<T extends Object> constructor

Sync<T extends Object>(
  1. @mustBeAnonymous @noFuturesAllowed T noFuturesAllowed(), {
  2. @noFuturesAllowed Err<T> onError(
    1. Object? error
    )?,
  3. @noFuturesAllowed void onFinalize()?,
})

Creates a Sync executing a synchronous function noFuturesAllowed.

IMPORTANT:

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

Implementation

factory Sync(
  @mustBeAnonymous @noFuturesAllowed T Function() noFuturesAllowed, {
  @noFuturesAllowed Err<T> Function(Object? error)? onError,
  @noFuturesAllowed void Function()? onFinalize,
}) {
  assert(!_isSubtype<T, Future<Object>>(), '$T must never be a Future.');
  return Sync.unsafe(() {
    try {
      return Ok(noFuturesAllowed());
    } on Err catch (e) {
      return e.transfErr<T>();
    } catch (error) {
      try {
        if (onError == null) {
          rethrow;
        }
        return onError(error);
      } catch (e) {
        return Err<T>(e);
      }
    } finally {
      onFinalize?.call();
    }
  }());
}