Sub topic 10
Errors from other isolates
This chapter assumes you know basic Dart syntax, async and await, Futures, and how to build a Flutter app. It also assumes you know that an isolate is Dart's independent unit of execution.
An isolate has its own memory, event loop, and uncaught-error handlers. Isolates do not share normal variables with one another. For example, a worker isolate created with Isolate.spawn cannot directly call the FlutterError.onError handler installed in the main isolate.
Registering an error listener
When you create an isolate, give it an error listener. The listener receives a message containing the error and its stack trace. The message is normally a two-item list:
- Item zero is the error object.
- Item one is the stack trace, represented as a string.
The following example starts a worker that throws an uncaught error. The main isolate receives and prints that error.
import 'dart:isolate';
import 'package:flutter/foundation.dart';
void failingWorker(Object? message) {
throw StateError('The worker isolate failed');
}
Future<Isolate> startFailingWorker() async {
final errorPort = RawReceivePort((dynamic message) {
if (message is List && message.length >= 2) {
final Object error = message[0];
final String stack = message[1].toString();
debugPrint('Worker error: $error');
debugPrint('Worker stack:\n$stack');
// Send error and stack to your reporting service here.
}
});
final isolate = await Isolate.spawn<Object?>(
failingWorker,
null,
onError: errorPort.sendPort,
);
return isolate;
}RawReceivePort is a low-level receive port. Its callback runs when a message arrives on the port. The onError argument to Isolate.spawn connects the worker's uncaught errors to that port.
Keep the RawReceivePort open while the worker can still run. Closing it too early prevents later errors from being received. In production code, close the port when the worker exits and no longer needs monitoring. You can use an additional onExit port to detect that condition.
Forwarding errors to one reporter
Your Flutter error handlers and isolate listeners should use the same reporting code. This keeps the format consistent and makes it easier to replace debug logging with a crash-reporting SDK.
class ErrorReporter {
static void reportIsolateError(Object error, String stack) {
debugPrint('isolate exception: $error');
debugPrint('isolate stack: $stack');
// Example replacement:
// crashService.record(error, StackTrace.fromString(stack));
}
}The isolate callback can then call ErrorReporter.reportIsolateError instead of containing the reporting details itself. Do not assume that a global handler in main() automatically sees worker-isolate failures. Forward each worker error explicitly.
Listening to the current isolate
Dart also lets you attach an error listener to the current isolate:
void listenToCurrentIsolateErrors() {
final port = RawReceivePort((dynamic message) {
if (message is List && message.length >= 2) {
ErrorReporter.reportIsolateError(
message[0] as Object,
message[1].toString(),
);
}
});
Isolate.current.addErrorListener(port.sendPort);
}This is a low-level Dart mechanism. It does not replace FlutterError.onError or PlatformDispatcher.instance.onError. Those Flutter handlers provide useful Flutter-specific details and behavior for errors in the main isolate. Use an isolate listener when you need to observe errors from an isolate that you created or otherwise control.
Limits and cleanup
An isolate error listener reports an uncaught error, but it does not make the worker healthy. The worker may stop, depending on its configuration and the error policy. Your application must decide whether to restart it, show fallback content, or stop the related operation.
Isolates also do not share zones. A runZonedGuarded callback in the main isolate cannot automatically guard code running in a worker isolate. Install a listener for every worker whose failures matter, and send structured messages back when the worker completes normally or fails.
Exercise
Why does an uncaught error in a spawned isolate not automatically reach PlatformDispatcher.instance.onError in the main isolate?
Show answer
Each isolate has its own memory and error-handling context. The parent must register an error listener for the worker and forward the received error to its reporting code.