Sub topic 10
Errors from other isolates
This chapter assumes you have already installed FlutterError.onError and PlatformDispatcher.instance.onError in main(), as covered in the earlier chapters. You should also know async/await, Future, and how Dart isolates pass messages. This chapter covers errors raised in isolates other than the main one, which those two handlers do not see.
Why the global handlers do not cover other isolates
A Dart isolate has its own memory, its own event loop, and its own copy of every static variable. FlutterError.onError is a static field. When you assign it in main(), you set it only in the main isolate. A worker isolate starts with the default value, which prints to the console.
Three consequences follow:
- An uncaught exception in a worker never reaches your handlers in the main isolate on its own.
- By default,
Isolate.spawnmakes uncaught errors fatal. The worker stops, and the main isolate gets no signal. - Assigning
FlutterError.onErrorinside a worker only changes that worker's copy. It does not help the main isolate.
You must therefore route worker errors to the main isolate yourself. The mechanism depends on how you started the worker.
| How the work runs | Where an uncaught error appears | What you do |
|---|---|---|
| `Isolate.run` or `compute` | As the error of the returned `Future` | `await` it in `try`/`catch`. If nobody does, it reaches `PlatformDispatcher.onError`. |
| `Isolate.spawn` with `onError:` | As a message on the port you supplied | Listen on that port and report. |
| `Isolate.spawn` without `onError:` | Nowhere. The error is printed in the worker, and the worker stops. | Add a listener, or catch inside the entry function. |
| The main isolate itself | `PlatformDispatcher.onError` or `FlutterError.onError` | Already handled by the earlier chapters. |
Short-lived work: Isolate.run and compute
For one-off computations, Isolate.run does the routing for you. It starts a worker, runs your function, sends the result back, and shuts the worker down. If the function throws, the error is sent back and the returned Future completes with it.
import 'dart:isolate';
import 'package:flutter/foundation.dart';
Future<int> parseInBackground(String text) async {
try {
return await Isolate.run(() => int.parse(text));
} on FormatException catch (e) {
debugPrint('Bad input: ${e.message}');
return -1;
} catch (e, stack) {
// Errors that cannot be copied between isolates may arrive
// wrapped in a RemoteError instead of their original type.
debugPrint('Worker failed: $e\n$stack');
rethrow;
}
}The error arrives as an ordinary asynchronous error, so everything you already know applies. A try/catch around the await handles it. If you call Isolate.run(...) and never await or catch the future, the error becomes an uncaught asynchronous error in the main isolate. PlatformDispatcher.instance.onError then receives it. compute() from package:flutter/foundation.dart behaves the same way.
Error types usually survive the trip, but not always. An error object that cannot be sent across isolates may arrive as a RemoteError. A RemoteError carries the error text and stack trace as strings. Do not rely on a specific on MyException clause for errors that cross an isolate boundary unless you have tested it.
Long-lived workers: Isolate.spawn and error ports
With Isolate.spawn, you pass a SendPort as onError:. The worker sends every uncaught error to that port. Each message is a list of two items: the error as a string and the stack trace as a string. The stack trace string can be null.
Because both items are strings, the original exception type is gone. You get text such as Bad state: Worker A failed, not a StateError.
The next example spawns a worker, listens for its errors, and cleans up when it exits. It forwards each error into FlutterError.reportError, so worker errors follow the same path as framework errors.
import 'dart:isolate';
import 'package:flutter/foundation.dart';
/// Entry point for the worker. It must be a top-level or static function.
void crashingWorker(String label) {
throw StateError('Worker $label failed');
}
Future<Isolate> spawnReported(
void Function(String) entry,
String argument,
) async {
final errorPort = RawReceivePort();
final exitPort = RawReceivePort();
void closePorts() {
errorPort.close();
exitPort.close();
}
errorPort.handler = (dynamic message) {
final pair = message as List<dynamic>;
final String errorText = pair.first as String;
final String? stackText = pair.last as String?;
FlutterError.reportError(
FlutterErrorDetails(
exception: errorText,
stack: StackTrace.fromString(stackText ?? ''),
library: 'worker isolate',
context: ErrorDescription('while running $argument'),
),
);
};
// The worker sends an exit message after it stops, normally or after an error.
exitPort.handler = (dynamic _) => closePorts();
try {
return await Isolate.spawn<String>(
entry,
argument,
onError: errorPort.sendPort,
onExit: exitPort.sendPort,
);
} catch (_) {
closePorts(); // spawning itself failed, so no exit message will come
rethrow;
}
}Call it with spawnReported(crashingWorker, 'A'). Both port handlers run on the main isolate, so FlutterError.reportError calls the FlutterError.onError you installed there. Your reporting code then sees worker errors through the same pipeline as every other error.
Choosing the reporting path
Inside the port handler you have two reasonable choices:
FlutterError.reportError(details)sends the error throughFlutterError.onError. You get one pipeline and one place to filter or sample. The cost is that worker errors look like framework errors in your dashboard unless you setlibraryandcontext, as the example does.- Calling your
ErrorReporterdirectly keeps worker errors separate. Use it when you want different tags, rate limits, or severity for background work.
Either choice works. Pick one and use it consistently.
Fatal or not
The errorsAreFatal parameter of Isolate.spawn defaults to true. The worker stops after the first uncaught error, and you receive one error message followed by the exit message. If you set errorsAreFatal: false, the worker keeps running after an error. This suits a worker that handles many independent jobs, but a bug that throws on every message then produces a flood of reports. Add a counter or a time window in the port handler before you forward each report.
Catching errors inside the worker
An error port is a safety net. For workers whose results you depend on, catch errors inside the entry function and send them back as ordinary messages. That preserves the error type and lets you attach context such as the job ID.
import 'dart:isolate';
void safeWorker(List<Object> args) {
final SendPort replyTo = args[0] as SendPort;
final int value = args[1] as int;
try {
replyTo.send(<String, Object?>{'ok': 100 ~/ value});
} on IntegerDivisionByZeroException {
replyTo.send(<String, Object?>{'error': 'division by zero', 'input': value});
} catch (e, stack) {
replyTo.send(<String, Object?>{'error': '$e', 'stack': '$stack'});
}
}The reply is a plain map, which is always sendable. The receiving side checks for an error key and reports it. Keep the error port too, for failures you did not anticipate.
Listening for errors on the main isolate
You can also attach an error listener to the main isolate. The fifth code example of the plan does this with Isolate.current.addErrorListener:
import 'dart:isolate';
import 'package:flutter/foundation.dart';
void listenToMainIsolateErrors() {
Isolate.current.addErrorListener(RawReceivePort((dynamic pair) {
final List<dynamic> errorAndStacktrace = pair as List<dynamic>;
debugPrint('Isolate error: ${errorAndStacktrace.first}');
debugPrint('Stack: ${errorAndStacktrace.last}');
}).sendPort);
}Call it once in main(), after WidgetsFlutterBinding.ensureInitialized(). It receives the same two-string message as the worker example, so the original exception type is again lost.
This listener overlaps with PlatformDispatcher.instance.onError. Depending on the Flutter version and on what your handler returns, the same error may show up in both places. If you install both, test with a deliberate error, as described in the testing chapter. Count how many reports arrive, and remove one channel if you see duplicates. For most apps, PlatformDispatcher.instance.onError alone is enough on the main isolate.
Pitfalls specific to isolates
- Forgetting the listener. A worker started with plain
Isolate.spawn(entry, arg)fails silently from your app's point of view. Always passonError:or catch inside the entry function. - Leaking ports. A
RawReceivePortstays open until you close it. Close it from theonExithandler, and also whenspawnitself throws. - Expecting typed errors. Error port messages contain strings. If your reporting code branches on
error is TimeoutException, it will never match for worker errors received this way. - Installing handlers in the worker. Assigning
FlutterError.onErrorin a worker changes that worker's static field only. The worker also has no Flutter binding unless you initialize one. Report through a port instead. - Unsendable data. Closures passed to
Isolate.runcopy everything they capture. If the closure captures an object that cannot be sent, such as one holding a native handle, the call fails. That failure is itself an error, so keep thetry/catch. - Stack traces from obfuscated builds. If you build with
--obfuscate, the stack strings from workers are as unreadable as those from the main isolate. Keep your symbol files and symbolicate them in your reporting service.
Summary
- Static state, including
FlutterError.onError, is per isolate, so the handlers frommain()do not see worker errors. Isolate.runandcomputereturn errors through the future. Handle them withtry/catch, or let them fall through toPlatformDispatcher.onError.Isolate.spawnneedsonError:with a port you listen on. Messages are a list of an error string and a nullable stack string, so the exception type is lost.- Forward port messages to your single reporting pipeline, either through
FlutterError.reportErroror directly. - Close ports on exit, and rate-limit reports when
errorsAreFatalisfalse.
Exercise
A teammate starts a background worker with Isolate.spawn(importContacts, path) and installs FlutterError.onError and PlatformDispatcher.instance.onError in main(). When importContacts throws, nothing is reported. Give two different fixes, and say what information each one preserves or loses.
Show answer
First fix: pass onError: with the sendPort of a RawReceivePort (and onExit: to close it), then forward each message to the reporter. The message is a list of an error string and a stack string, so the exception type is lost. Second fix: wrap the body of importContacts in try/catch and send the failure back to the main isolate as a normal message. This keeps the exception type and lets you add context, such as which file failed. The global handlers did not fire because they are static fields in the main isolate, and the worker has its own copies and its own event loop.
Exercise
You call Isolate.run(() => heavyParse(data)) in a button handler without await and without catch. heavyParse throws. Which of your global handlers receives the error, and why?
Show answer
PlatformDispatcher.instance.onError. Isolate.run returns a Future that completes with the worker's error. Nothing listens to that future, so the error is an uncaught asynchronous error in the main isolate, which is the case PlatformDispatcher.instance.onError handles. FlutterError.onError does not receive it, because no framework code caught it.