Sub topic 7
Handling errors from an isolate
This chapter assumes you can use Isolate.run, know the difference between an Exception and an Error, and have seen try/catch with await. It covers what happens to a failure that starts in another isolate: where it surfaces, what survives the trip, and how to report errors from a long-lived worker.
The basic rule: errors come back through the Future
An isolate has its own heap and its own event loop. An exception thrown there cannot unwind the call stack of the isolate that started it. Isolate.run bridges the gap. If the closure throws, the worker isolate catches the error and sends the error and its stack trace back to the caller. The Future returned by Isolate.run then completes with that error, so your ordinary try/catch works.
import 'dart:isolate';
Future<void> main() async {
try {
await Isolate.run(() {
throw const FormatException('bad input');
});
} on FormatException catch (e) {
print('Caught from isolate: ${e.message}');
}
}The error you catch is a copy of the original object, with its type intact. That is why on FormatException matches. The worker isolate shuts down after the failure, and no cleanup is needed on your side.
What survives the trip
The error object is sent as a message, so the rules from the chapter on sendable messages apply to it. Most built-in exceptions and errors (FormatException, ArgumentError, StateError, RangeError) copy without trouble. A custom exception also copies if its fields are sendable.
import 'dart:isolate';
class ImportException implements Exception {
ImportException(this.line, this.reason);
final int line;
final String reason;
@override
String toString() => 'ImportException(line $line): $reason';
}
int importRows(List<String> rows) {
var count = 0;
for (var i = 0; i < rows.length; i++) {
if (rows[i].isEmpty) throw ImportException(i + 1, 'empty row');
count++;
}
return count;
}
Future<void> main() async {
final rows = ['a,1', 'b,2', '', 'd,4'];
try {
final count = await Isolate.run(() => importRows(rows));
print('Imported $count rows');
} on ImportException catch (e, stack) {
print('Failed at line ${e.line}: ${e.reason}');
print('Worker stack has ${stack.toString().split('\n').length} lines');
}
}The stack trace you receive describes where the error happened inside the worker isolate. It is useful for debugging. It does not include the frames of the code that called Isolate.run, because that call stack lives in a different isolate.
Keep custom exceptions small and made of plain data such as numbers, strings, lists and maps. If an exception holds a ReceivePort, a native resource, or a reference to a large object graph, sending it can fail or become expensive. In that case, convert the failure to a simple value inside the closure before it leaves the worker.
Errors that do not look like your error
Not every failure arrives as the original object. The table lists what the caller sees in the common cases.
| What went wrong in the worker | What the caller's Future does |
|---|---|
| The closure throws synchronously, or an `async` closure's returned future fails | Completes with the original error and its stack trace |
| An error escapes in a separate asynchronous callback, such as a `Timer` or an unawaited future | Completes with a `RemoteError`, which holds only the error text and stack text as strings |
| The isolate ends without producing a result | Completes with a `RemoteError` whose description says the computation ended without a result |
| The result or the error cannot be sent | Completes with an error describing the failed send |
RemoteError is declared in dart:isolate. Because it carries strings, you cannot match on the original type. You can only log it or show a generic message.
import 'dart:isolate';
Future<void> main() async {
try {
await Isolate.run(() async {
await Future<void>.delayed(const Duration(milliseconds: 10));
throw StateError('worker failed');
});
} on StateError catch (e) {
// An error from an awaited async closure keeps its type.
print('Typed: ${e.message}');
} on RemoteError catch (e) {
// Errors that escape outside the awaited chain arrive as text.
print('Remote: ${e.toString()}');
}
}Here the closure is async and the error is part of its awaited chain, so the typed StateError comes back. Order your on clauses from the specific type to RemoteError, and add a final generic catch if you must not let anything escape.
Compute behaves the same way
In Flutter, compute follows the same pattern. An error thrown by the callback makes the returned future complete with that error, so you can wrap await compute(...) in try/catch. The same sendability rules apply, and compute only offers a way to pass a single argument. On the web, compute runs the callback on the same thread, so the error reaches you through the normal call path.
Timeouts do not cancel the work
A common mistake is to add .timeout(...) to the future and assume the isolate stops.
import 'dart:isolate';
Future<int> slowSum() => Isolate.run(() {
var s = 0;
for (var i = 0; i < 4000000000; i++) {
s += i;
}
return s;
});
Future<void> main() async {
try {
await slowSum().timeout(const Duration(seconds: 1));
} on Exception catch (e) {
print('Gave up waiting: ${e.runtimeType}');
}
}After one second the caller gets a TimeoutException and stops waiting. The worker isolate still runs until the loop finishes, using a CPU core and memory. Isolate.run gives you no handle to cancel it. If you need real cancellation, spawn the isolate yourself with Isolate.spawn, keep the Isolate object, and call kill() on it when you give up.
Errors in long-lived workers
A worker built with Isolate.spawn and ports has no Future to carry its errors. You have two layers to handle.
- Expected failures. Catch them inside the worker, for each job, and send them back as part of the reply message. The worker stays alive and can take the next job.
- Unexpected failures. Anything uncaught ends the isolate, because
errorsAreFataldefaults totrue. Pass a port toonErrorso the main isolate hears about it. Each message on that port is a list of two strings: the error text and the stack trace text.
The example below combines both layers. Each reply is a record (id, value, error), where exactly one of value and error is non-null.
import 'dart:isolate';
int _parsePositive(String text) {
final n = int.parse(text);
if (n < 0) throw ArgumentError.value(n, 'text', 'must not be negative');
return n;
}
void _worker(SendPort toMain) {
final commands = ReceivePort();
toMain.send(commands.sendPort);
commands.listen((message) {
if (message == null) {
commands.close();
return;
}
final (id, text) = message as (int, String);
try {
toMain.send((id, _parsePositive(text), null));
} catch (e) {
// Send text, not the exception object, so the reply is always sendable.
toMain.send((id, null, e.toString()));
}
});
}
Future<void> main() async {
final fromWorker = ReceivePort();
final uncaught = ReceivePort();
await Isolate.spawn(_worker, fromWorker.sendPort, onError: uncaught.sendPort);
uncaught.listen((e) {
final list = e as List<dynamic>;
print('Worker died: ${list[0]}');
});
final events = StreamIterator<dynamic>(fromWorker);
await events.moveNext();
final toWorker = events.current as SendPort;
for (final (id, text) in [(1, '42'), (2, 'abc'), (3, '-5')]) {
toWorker.send((id, text));
await events.moveNext();
final (replyId, value, error) = events.current as (int, int?, String?);
if (error != null) {
print('job $replyId failed: ${error.split('\n').first}');
} else {
print('job $replyId -> $value');
}
}
toWorker.send(null);
await events.cancel();
uncaught.close();
}Jobs 2 and 3 fail, but the worker still answers job 3 after job 2 failed, because the try/catch sits inside the message handler. Only an error that escapes that handler reaches uncaught.
Two design points matter here:
- Match replies to requests. The
idin each message lets the caller pair an error with the job that caused it. With several jobs in flight, this is the only way to know which one failed. - Choose the error format on purpose. A string is always safe to send. If the caller needs to branch on the kind of failure, send a small code or a record such as
('parse', 'message')instead of the exception object.
You can also pass onExit to Isolate.spawn to receive a message when the isolate ends for any reason. Combine it with onError to detect a worker that died, then restart it and fail the jobs that were waiting.
Practical checklist
- Wrap every
await Isolate.run(...)orawait compute(...)intry/catchif the work can fail on bad input. - Catch specific types first, then
RemoteError, then a general fallback. - Throw small, plain-data exceptions from inside the closure.
- Do not rely on
.timeoutto stop work. - In a long-lived worker, catch per job and reply with an id, and listen on
onErrorfor fatal failures.
Exercise
A caller runs await Isolate.run(() => work()).timeout(const Duration(seconds: 2)). The work takes 30 seconds and later throws an ArgumentError. What does the caller see at the 2-second mark, what happens to the worker, and which Isolate API would let you cancel it?
Show answer
At 2 seconds the caller's Future completes with a TimeoutException. The worker isolate keeps running, because timeout only stops the caller from waiting, and Isolate.run returns no handle for cancelling. The later ArgumentError is not delivered to the caller's await, which already failed. To cancel, start the worker with Isolate.spawn, keep the returned Isolate, and call kill() on it when the timeout fires.
Exercise
In the long-lived worker example, why does the worker send e.toString() instead of the caught exception object, and what would you change if the caller needed to react differently to a FormatException than to an ArgumentError?
Show answer
A string is always sendable and small, so the reply cannot fail because of an unsendable field in the exception. To let the caller branch on the failure kind, send a plain-data code along with the text, for example the record (id, null, ('format', e.toString())) or a short string such as 'format' or 'argument'. The caller then switches on that code rather than on an exception type.