8760283247
A combination of `runZoned` and `runZonedGuarded` where only the latter allows an `onError` parameter, and only that has a nullable return type. Retains the `onError` parameter on `runZoned` for now because it's too breaking to remove it until packages have been migrated off of it. It will be removed in a follow-up CL. Change-Id: If0e86c8d14e13fa089c66f4af975aeacb2616cf6 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/137302 Reviewed-by: Jake Macdonald <jakemac@google.com> Reviewed-by: Nate Bosch <nbosch@google.com>
56 lines
1.5 KiB
Dart
56 lines
1.5 KiB
Dart
library catch_errors;
|
|
|
|
import 'dart:async';
|
|
|
|
Stream catchErrors(dynamic body()) {
|
|
StreamController controller;
|
|
|
|
bool onError(e, st) {
|
|
controller.add(e);
|
|
return true;
|
|
}
|
|
|
|
void onListen() {
|
|
runZonedGuarded(body, onError);
|
|
}
|
|
|
|
controller = new StreamController(onListen: onListen);
|
|
return controller.stream;
|
|
}
|
|
|
|
runZonedScheduleMicrotask(body(),
|
|
{void onScheduleMicrotask(void callback()), Function? onError}) {
|
|
if (onScheduleMicrotask == null) {
|
|
return runZonedGuarded(body, onError);
|
|
}
|
|
HandleUncaughtErrorHandler errorHandler;
|
|
if (onError != null) {
|
|
errorHandler = (Zone self, ZoneDelegate parent, Zone zone, error,
|
|
StackTrace stackTrace) {
|
|
try {
|
|
return self.parent.runUnary(onError, error);
|
|
} catch (e, s) {
|
|
if (identical(e, error)) {
|
|
return parent.handleUncaughtError(zone, error, stackTrace);
|
|
} else {
|
|
return parent.handleUncaughtError(zone, e, s);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
ScheduleMicrotaskHandler asyncHandler;
|
|
if (onScheduleMicrotask != null) {
|
|
asyncHandler = (Zone self, ZoneDelegate parent, Zone zone, f()) {
|
|
self.parent.runUnary(onScheduleMicrotask, () => zone.runGuarded(f));
|
|
};
|
|
}
|
|
ZoneSpecification specification = new ZoneSpecification(
|
|
handleUncaughtError: errorHandler, scheduleMicrotask: asyncHandler);
|
|
Zone zone = Zone.current.fork(specification: specification);
|
|
if (onError != null) {
|
|
return zone.runGuarded(body);
|
|
} else {
|
|
return zone.run(body);
|
|
}
|
|
}
|