Sub topic 7
Handling errors from an isolate
This chapter assumes basic Dart syntax, async and await, Future, and basic streams. You should also understand that an isolate has its own memory and communicates with other isolates by messages.
Errors from `Isolate.run`
Isolate.run returns a Future. If the callback throws, that Future completes with an error. The calling isolate can handle it with ordinary try and catch syntax.
Place await inside the try block. Without await, the try block ends before the asynchronous operation reports its error.
import 'dart:isolate';
Future<String> loadRecord() {
return Isolate.run(() {
throw const FormatException('The record is not valid JSON');
});
}
Future<void> main() async {
try {
final record = await loadRecord();
print(record);
} on FormatException catch (error, stackTrace) {
print('Could not load record: ${error.message}');
print(stackTrace);
} catch (error, stackTrace) {
print('Unexpected isolate error: $error');
print(stackTrace);
}
}The on FormatException branch handles the expected input error. The general catch branch protects the caller from unexpected failures. Catching an error does not repair the failed computation. Your application still needs to decide whether to show an error, retry, use cached data, or stop the operation.
A useful boundary is to convert low-level errors into an application-level result:
sealed class ParseResult {}
class ParseSuccess extends ParseResult {
ParseSuccess(this.value);
final int value;
}
class ParseFailure extends ParseResult {
ParseFailure(this.message);
final String message;
}
Future<ParseResult> parseInBackground(String input) async {
try {
final value = await Isolate.run(() {
final number = int.parse(input);
return number * 2;
});
return ParseSuccess(value);
} on FormatException {
return ParseFailure('Enter a whole number.');
}
}This keeps isolate details out of the user-interface layer.
Preserving useful diagnostics
Catch both the error and its StackTrace when logging or reporting a failure. The stack trace points to the code that failed inside the worker callback. Do not display raw stack traces to users, but keep them in development logs or an error-reporting service.
Errors can also occur before the callback starts, while preparing arguments, or after the result returns. Keep the whole operation inside the try block when those stages should receive the same handling.
| Operation | Typical handling |
|---|---|
| Expected invalid input | Catch a specific exception and show a useful message |
| Unexpected callback failure | Catch broadly, log the stack trace, and fail safely |
| Worker setup or message failure | Handle the port error and clean up resources |
Errors with `Isolate.spawn`
A long-lived isolate does not return each job as a Future. It sends messages through ports. Configure an error port when spawning it. Uncaught errors are delivered as a two-item message containing the error and its stack trace.
import 'dart:isolate';
void failingWorker(Object? message) {
throw StateError('Worker initialization failed');
}
Future<void> main() async {
final errors = ReceivePort();
await Isolate.spawn(
failingWorker,
null,
onError: errors.sendPort,
);
final event = await errors.first as List<dynamic>;
final error = event[0];
final stackTrace = event[1];
print('Worker error: $error');
print('Worker stack: $stackTrace');
errors.close();
}An error port reports failures; it does not automatically restart the isolate or retry a job. A worker protocol should define what happens next. For example, the main isolate might mark the current request as failed, reject queued requests, and create a replacement worker.
Avoiding lost errors
A common mistake is listening only for successful results. A worker can stop without producing the response that a caller expects. Track each request with an identifier and arrange a failure response or timeout.
For Isolate.run, the Future already provides a clear success-or-error boundary:
Exercise
Exercise
Why must await Isolate.run(...) usually appear inside the try block that handles its errors?
Show answer
The isolate reports its result through the returned Future. Awaiting that Future inside the try block lets the asynchronous error be caught there.