scope<S> method

Future<S> scope<S>(
  1. FutureOr<S> process(
    1. ErrNotifier<T>
    ), {
  2. bool errorIf(
    1. S,
    2. T?
    )?,
  3. bool criticalIf(
    1. S,
    2. T?
    )?,
  4. void onError(
    1. S,
    2. T?
    )?,
  5. void onCriticalError(
    1. S,
    2. T?
    )?,
})

Executes the provided function process, and then calls either of the onError and onCriticalError callbacks if the condition specified by errorIf or criticalIf is met respectively at the point when the process ends.

An object of ErrNotifier is passed to process to allow to call ErrNotifier.set() or ErrNotifier.log() on the object. Use the object also to access to ErrNotifier.lastError to see what the most recent error was. If there was no error, ErrNotifier.lastError holds the default value specified in the constructor of ErrFlow.

All of the other parameters are also functions, which receive the result of the process and the last error set inside it. If there is no error, the default value is provided as the last error.

onError (or errorHandler if onError is not specified) is called if errorIf returns true, and similarly, onCriticalError (or criticalErrorHandler) is called if criticalIf returns true. The condition of criticalIf is evaluated prior to that of errorIf, and the latter is ignored if the former condition is met.

Implementation

Future<S> scope<S>(
  FutureOr<S> Function(ErrNotifier<T>) process, {
  bool Function(S, T?)? errorIf,
  bool Function(S, T?)? criticalIf,
  void Function(S, T?)? onError,
  void Function(S, T?)? onCriticalError,
}) async {
  assert(_debugAssertNotDisposed());
  assert(
    errorIf == null || onError != null || errorHandler != null,
    'The handler for non-critical errors is missing while `errorIf` '
    'is specified.\n'
    'To fix, set the default or a custom handler by assigning it '
    'to `errorHandler`.',
  );
  assert(
    criticalIf == null ||
        onCriticalError != null ||
        criticalErrorHandler != null,
    'The handler for critical errors is missing while `criticalErrorIf` '
    'is specified.\n'
    'To fix, set the default or a custom handler by assigning it to '
    '`criticalErrorHandler`.',
  );

  final newNotifier = Notifier.from(_notifier);
  final result = await process(newNotifier);
  final error = newNotifier.lastError;

  // NOTE: criticalIf must be evaluated ahead of errorIf.
  if (criticalIf != null && criticalIf(result, error)) {
    onCriticalError == null
        ? criticalErrorHandler!(result, error)
        : onCriticalError(result, error);
  } else if (errorIf != null && errorIf(result, error)) {
    onError == null ? errorHandler!(result, error) : onError(result, error);
  }

  newNotifier.dispose();

  return result;
}