catchTopLevelErrors function

void catchTopLevelErrors(
  1. void callback(),
  2. void onError(
    1. dynamic error,
    2. StackTrace
    )
)

Run callback and capture any errors that would otherwise be top-leveled.

If this is called in a non-root error zone, it will just run callback and return the result. Otherwise, it will capture any errors using runZoned and pass them to onError.

Implementation

void catchTopLevelErrors(
  final void Function() callback,
  final void Function(dynamic error, StackTrace) onError,
) {
  if (Zone.current.inSameErrorZone(Zone.root)) {
    return runZonedGuarded(callback, onError);
  } else {
    return callback();
  }
}