Sub topic 5
Handling async errors with PlatformDispatcher.instance.onError
This chapter assumes you know Dart async/await and Future, can build a small Flutter app with runApp, and are comfortable with try/catch. You should also know that FlutterError.onError receives errors the framework catches itself. This chapter covers the other channel: errors that nothing catches.
Why a second handler is needed
The Flutter framework wraps its own work in try/catch. Building, layout, painting, and synchronous gesture callbacks all run inside that protection. When one of them throws, the framework wraps the exception in a FlutterErrorDetails and hands it to FlutterError.onError.
Asynchronous code is different. Consider a button callback declared async. The framework calls it and gets back a Future. It does not await that Future, so a failure inside it never passes through the framework's try/catch. The same applies to a Timer callback, a stream listener with no error handler, or a Future created and forgotten.
Dart does not drop these errors. Each failure is reported to the zone the code was running in. A zone is Dart's execution context for asynchronous work, and it decides what happens to uncaught errors. For code in the default (root) zone, the error is forwarded to PlatformDispatcher.instance.onError. PlatformDispatcher is the dart:ui class that connects your Dart code to the platform embedder, and onError is its hook for errors nobody handled.
The signature is:
typedef ErrorCallback = bool Function(Object exception, StackTrace stackTrace);Unlike FlutterError.onError, you get no FlutterErrorDetails. You receive a bare exception and a stack trace, with no library or context fields. If you need to know where the error came from, you must infer it from the stack.
Installing the handler
You assign a function to PlatformDispatcher.instance.onError, normally in main() before runApp. Call WidgetsFlutterBinding.ensureInitialized() first. This is the convention for everything that touches the engine, and it prevents ordering problems if you later add plugin calls or runZonedGuarded to main.
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
debugPrint('Uncaught async error: $error\n$stack');
return true; // true means "handled"
};
runApp(const MaterialApp(home: Scaffold(body: Center(child: Text('Hello')))));
}PlatformDispatcher lives in dart:ui, so the import 'dart:ui'; line is required. The Material library does not export it. debugPrint comes from package:flutter/foundation.dart, which material.dart also re-exports, so that import is optional but harmless.
The handler is a single slot. Assigning to it replaces whatever was there, including a handler installed by a crash-reporting SDK. If you use such an SDK, read its setup instructions before assigning the slot yourself.
The return value
The callback must return a bool:
| Return | Meaning | What happens next |
|---|---|---|
| `true` | You handled the error. | Nothing more. The error is considered consumed. |
| `false` | You did not handle it. | The engine falls back to its default reporting. |
Returning true is right when you have logged or reported the error and want the app to continue. Returning false is right when your handler only observes the error and you want the default behavior to continue as well.
The default behavior is tuned for development. In debug mode it prints the error to the console. Do not rely on it as your release-mode reporting path. If the error matters, report it yourself in the handler.
A handler that returns true for everything can hide bugs during development, because the console no longer shows a red error. That is why the examples in this chapter print with debugPrint before returning.
Worked example: four ways to fail
The next program triggers four failures from buttons. Three are uncaught asynchronous errors, and one is caught by the caller. The handler writes the latest error into a ValueNotifier, so you can see on screen which ones arrived.
import 'dart:async';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
final ValueNotifier<String> lastAsyncError = ValueNotifier<String>('none yet');
void main() {
WidgetsFlutterBinding.ensureInitialized();
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
debugPrint('Uncaught async error: $error\n$stack');
lastAsyncError.value = error.toString();
return true;
};
runApp(const AsyncErrorDemo());
}
Future<void> failingTask(String label) async {
await Future<void>.delayed(const Duration(milliseconds: 100));
throw StateError('failure in $label');
}
class AsyncErrorDemo extends StatelessWidget {
const AsyncErrorDemo({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ValueListenableBuilder<String>(
valueListenable: lastAsyncError,
builder: (context, value, _) => Text('Last error: $value'),
),
const SizedBox(height: 16),
ElevatedButton(
// Future is dropped: nobody awaits it, so the error is uncaught.
onPressed: () => failingTask('dropped future'),
child: const Text('1. Dropped Future'),
),
ElevatedButton(
// A Timer callback that throws is uncaught by definition.
onPressed: () => Timer(
const Duration(milliseconds: 100),
() => throw StateError('failure in timer'),
),
child: const Text('2. Timer callback'),
),
ElevatedButton(
// A stream error with no onError handler on listen is uncaught.
onPressed: () => Stream<int>.error(StateError('failure in stream'))
.listen((_) {}),
child: const Text('3. Stream without onError'),
),
ElevatedButton(
// Awaited inside try/catch: the global handler never sees this.
onPressed: () async {
try {
await failingTask('caught future');
} catch (e) {
lastAsyncError.value = 'caught locally: $e';
}
},
child: const Text('4. Caught locally'),
),
],
),
),
),
);
}
}Run it and press each button. Buttons 1, 2, and 3 print Uncaught async error: to the console and update the text. Button 4 updates the text through its own catch, and no Uncaught async error: line appears. That last case is the central rule: the global handler is a last resort, and anything your code already handles never reaches it.
Notice that button 1 uses an arrow function that returns the Future from failingTask. onPressed has the type VoidCallback, so Dart ignores the returned value. The Future still fails, and nobody listens to it.
Reporting from the handler
In a real app, the handler forwards the error to a logging or crash-reporting service. Keep the handler thin and put the work in one place, so both global handlers can share it.
import 'dart:ui';
import 'package:flutter/foundation.dart';
class ErrorReporter {
static bool reportAsyncError(Object error, StackTrace stack) {
// Replace with a call to your logging or crash-reporting service.
debugPrint('error: $error');
debugPrint('stack: $stack');
return true;
}
}
void installAsyncErrorHandler() {
PlatformDispatcher.instance.onError = ErrorReporter.reportAsyncError;
}Because the callback type is bool Function(Object, StackTrace), a static method with that signature can be assigned directly, with no wrapper closure.
Two details matter for reporting. First, report the stack trace along with the error. A message like Bad state: failure in timer is rarely enough to find the cause. Second, if your reporting call is itself asynchronous, do not await it inside the handler. The handler is synchronous and returns a bool, so start the call and let it run. If that call can fail, give it its own error handling.
Errors from other isolates
An isolate is Dart's unit of concurrent execution, with its own memory and its own event loop. PlatformDispatcher.instance.onError covers the main isolate. An error thrown in an isolate you start with Isolate.spawn or compute does not reach it. Errors from the compute function are delivered as a failed Future to the caller, so they follow the normal rules above. For a manually spawned isolate, you attach an error listener to it. A later chapter covers this.
Common mistakes
- Handler throws. If your handler raises an exception, that new error is itself uncaught and can call the handler again. Keep the body simple. Wrap risky reporting calls in
try/catch. - Forgetting the return value. Dart will not compile a function that does not return a
boolhere, but a handler that returnsfalseby habit lets the default reporting run too. Choose the value on purpose. - Expecting
FlutterErrorDetails. The async handler gets only an error and a stack. Do not try to readdetails.libraryhere. - Assuming it catches everything. Errors you catch yourself, errors in other isolates, and errors in a custom zone with its own handler (the topic of a later chapter on
runZonedGuarded) do not arrive here. - Installing it too late. Assign the handler before
runApp. An error that fires earlier goes to the default handling. - Treating
trueas a fix. Returningtruestops the error from being reported by default. It does not repair the state the failed task left behind. A half-finished save is still half finished.
Checking your understanding
Exercise
A screen has this code: onPressed: () async { await fetchProfile(); }, where fetchProfile() throws a StateError after a network delay. Which global handler receives the error, and what single change would stop it from reaching that handler at all?
Show answer
PlatformDispatcher.instance.onError receives it. The framework calls the callback but does not await the returned Future, so the failure is uncaught asynchronous. Wrapping the await fetchProfile(); call in try/catch, or adding .catchError(...) to the Future, handles the error locally, and then neither global handler sees it.
Exercise
Your PlatformDispatcher.instance.onError handler logs the error and returns false. In the debug console you see your log line and the default error output. Why do you see both, and how do you suppress the default output?
Show answer
Returning false tells the engine the error was not handled, so it applies its default reporting after your handler runs. Return true to mark the error as handled and suppress the default output.