errors property

Stream errors

A broadcast stream of uncaught errors from the isolate.

When listening on the stream, errors from the isolate will be reported as errors in the stream. Be ready to handle the errors.

The stream closes when the isolate shuts down.

Implementation

Stream get errors {
  late StreamController controller;
  late RawReceivePort port;
  void handleError(message) {
    if (message == null) {
      // Isolate shutdown.
      port.close();
      controller.close();
    } else {
      // Uncaught error.
      final errorDescription = message[0] as String;
      final stackDescription = message[1] as String;
      var error = RemoteError(errorDescription, stackDescription);
      controller.addError(error, error.stackTrace);
    }
  }

  controller = StreamController.broadcast(
      sync: true,
      onListen: () {
        port = RawReceivePort(handleError);
        isolate.addErrorListener(port.sendPort);
        isolate.addOnExitListener(port.sendPort);
      },
      onCancel: () {
        isolate.removeErrorListener(port.sendPort);
        isolate.removeOnExitListener(port.sendPort);
        port.close();
      });
  return controller.stream;
}