Sub topic 8
Triggering errors on purpose to verify both handlers
Installing FlutterError.onError and PlatformDispatcher.instance.onError is easy to get subtly wrong. A handler that is never reached looks the same as a handler that works, until a real crash goes unreported. This chapter builds a small error lab that fires one error of each kind and shows which handler received it. It also shows how to check the same thing in an automated test.
This chapter assumes you can write Dart with async/await and try/catch, and that you can build a small Flutter app with runApp. It also assumes you have installed both handlers in main() after WidgetsFlutterBinding.ensureInitialized().
What a good verification proves
A single "it printed something" check is not enough. You want to confirm four things:
- A synchronous error inside framework-run code reaches
FlutterError.onErrorand not the other handler. - A failed
Futurethat nobody listens to reachesPlatformDispatcher.instance.onError. - An error you catch yourself reaches neither handler.
- The handlers still work in a profile or release build, not only in debug.
The second and third points matter most. They show that the two channels are separate, and that your own try/catch takes priority over both.
Make the handlers observable
Printing to the console works, but a log shown on screen is easier to check, especially on a physical device in release mode. Start by pulling the installation into one function that takes a sink, a callback that receives each report. The app and the tests can then supply different sinks.
import 'dart:async';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
typedef ErrorSink = void Function(String channel, Object error);
void installErrorHandlers(ErrorSink sink) {
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details); // keep the default console output
sink('FlutterError.onError [${details.library}]', details.exception);
};
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
debugPrint('Uncaught async error: $error\n$stack');
sink('PlatformDispatcher.onError', error);
return true; // handled
};
}
final ValueNotifier<List<String>> errorLog = ValueNotifier<List<String>>(<String>[]);
void record(String channel, Object error) {
// Defer the update. An error thrown during build is reported while the
// framework is building, and notifying listeners at that moment would
// trigger a rebuild during build, which throws and reports again.
scheduleMicrotask(() {
errorLog.value = <String>[...errorLog.value, '$channel: $error'];
});
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
installErrorHandlers(record);
runApp(const LabApp());
}The scheduleMicrotask call is the one non-obvious line. A handler that changes UI state synchronously can turn one build error into an endless loop of errors. The pitfalls chapter returns to this. Here it is a practical constraint on any on-screen log.
details.library is a short string such as widgets library, gesture, or rendering library. It is a quick way to see which part of the framework caught the error.
The error lab screen
The page has one button per scenario. Two of them are controls, which are cases that must not reach either handler.
class LabApp extends StatelessWidget {
const LabApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(home: Scaffold(body: SafeArea(child: LabPage())));
}
}
class BrokenWidget extends StatelessWidget {
const BrokenWidget({super.key});
@override
Widget build(BuildContext context) {
throw StateError('build failed on purpose');
}
}
class LabPage extends StatefulWidget {
const LabPage({super.key});
@override
State<LabPage> createState() => _LabPageState();
}
class _LabPageState extends State<LabPage> {
bool _showBroken = false;
@override
Widget build(BuildContext context) {
return Column(
children: [
Wrap(
spacing: 8,
children: [
ElevatedButton(
onPressed: () => throw Exception('1: sync error in onPressed'),
child: const Text('1 Sync'),
),
ElevatedButton(
onPressed: () async {
await Future<void>.delayed(const Duration(milliseconds: 100));
throw StateError('2: async error after a delay');
},
child: const Text('2 Async'),
),
ElevatedButton(
onPressed: () => Timer(const Duration(milliseconds: 100), () {
throw StateError('3: error inside a Timer callback');
}),
child: const Text('3 Timer'),
),
ElevatedButton(
onPressed: () => setState(() => _showBroken = !_showBroken),
child: const Text('4 Build'),
),
ElevatedButton(
onPressed: () {
try {
throw Exception('5: caught by try/catch');
} catch (e) {
debugPrint('Handled locally: $e');
}
},
child: const Text('5 Caught'),
),
ElevatedButton(
onPressed: () {
Future<void>.error(StateError('6: handled by catchError'))
.catchError((Object e) => debugPrint('Handled locally: $e'));
},
child: const Text('6 catchError'),
),
TextButton(
onPressed: () => errorLog.value = <String>[],
child: const Text('Clear'),
),
],
),
if (_showBroken) const SizedBox(height: 80, child: BrokenWidget()),
Expanded(
child: ValueListenableBuilder<List<String>>(
valueListenable: errorLog,
builder: (context, entries, _) => ListView(
children: [for (final e in entries) ListTile(dense: true, title: Text(e))],
),
),
),
],
);
}
}Run it with flutter run, tap each button in turn, and compare the on-screen log with the table below.
Expected results
| Button | What happens | Handler that receives it |
|---|---|---|
| 1 Sync | The gesture system runs `onPressed`, catches the exception, and reports it | `FlutterError.onError`, library `gesture` |
| 2 Async | The async closure returns a `Future` that fails with no listener | `PlatformDispatcher.instance.onError` |
| 3 Timer | A timer callback throws in the root zone | `PlatformDispatcher.instance.onError` |
| 4 Build | `build` throws, the framework swaps in an `ErrorWidget` | `FlutterError.onError`, library `widgets library` |
| 5 Caught | Your `catch` consumes the error | Neither |
| 6 catchError | The `Future` has a listener that consumes the error | Neither |
Button 1 and button 2 look alike, since both are onPressed callbacks that throw. The difference is who is on the stack when the throw happens. In button 1 the framework is still running the callback, so it can catch the exception. In button 2 the throw happens after an await, when the callback has already returned a Future. The framework has nobody to catch the error, so it becomes an uncaught asynchronous error.
Reading the on-screen result
When button 1 fires, the log shows a line starting with FlutterError.onError [gesture] and the console also shows the usual framework error block. That block comes from presentError. If the console block is missing, you removed the presentError call, which is a valid choice but one to make deliberately.
When button 2 fires, the log shows PlatformDispatcher.onError, and the console shows only your own debugPrint lines. There is no default error block, because the handler returned true and told the engine the error was handled. To see the difference, change the return value to false, hot restart, and tap button 2 again. The engine now treats the error as unhandled and reports it through its default path.
Check release behavior
Debug mode adds assertions and a red error screen, and some framework checks run only in debug. Run the lab again as a release build:
flutter run --releaseTap buttons 1 to 6 and compare the log with the table. Two things change. Button 4 shows a gray box instead of a red screen, because ErrorWidget is less verbose in release mode. Debug-only reports such as layout overflow warnings no longer appear. The two handlers must still receive buttons 1 to 4, and the log should be identical for them. If an error reaches the log only in debug, your reporting depends on a debug-only code path.
Verify with automated tests
Manual taps are good for a first check. A test keeps the check from rotting. The handlers are global, so a test must restore the original values when it finishes. Otherwise the replaced handlers leak into later tests, and the test framework may complain about a changed FlutterError.onError.
Assume the app package is named error_lab and the code above is in lib/main.dart.
import 'dart:ui';
import 'package:error_lab/main.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('sync error in onPressed reaches FlutterError.onError', (tester) async {
final savedFlutter = FlutterError.onError;
final savedAsync = PlatformDispatcher.instance.onError;
final seen = <String>[];
try {
installErrorHandlers((channel, error) => seen.add(channel));
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: ElevatedButton(
onPressed: () => throw StateError('boom'),
child: const Text('Go'),
),
),
));
await tester.tap(find.text('Go'));
await tester.pump();
expect(seen, hasLength(1));
expect(seen.single, startsWith('FlutterError.onError'));
} finally {
FlutterError.onError = savedFlutter;
PlatformDispatcher.instance.onError = savedAsync;
}
});
test('async handler reports and returns true', () {
final savedFlutter = FlutterError.onError;
final savedAsync = PlatformDispatcher.instance.onError;
final seen = <String>[];
try {
installErrorHandlers((channel, error) => seen.add(channel));
final handled = PlatformDispatcher.instance.onError!(
StateError('boom'),
StackTrace.current,
);
expect(handled, isTrue);
expect(seen, <String>['PlatformDispatcher.onError']);
} finally {
FlutterError.onError = savedFlutter;
PlatformDispatcher.instance.onError = savedAsync;
}
});
}The second test calls the handler directly instead of throwing a real async error. Inside testWidgets, the test framework runs the body in its own zone and catches uncaught async errors itself. Those errors never reach PlatformDispatcher.instance.onError, so a real failing Future would test the test framework and not your handler. Calling the callback directly checks what you own: that it forwards the error and returns true.
For the real end-to-end path, use the manual lab or an integration test on a device. The unit tests then guard the handler logic.
Common mistakes when verifying
- Tapping a button before the handlers are installed. If the lab shows nothing, confirm that
installErrorHandlersruns beforerunApp. - Swallowing the error in your own code. A
try/catchor.catchErrorconsumes the error. Buttons 5 and 6 exist so you can see this on purpose. - Assuming every async failure reaches the handler. A
Futurewith any error listener, including one added later in the same event-loop turn, is not uncaught. Only errors with no listener reachPlatformDispatcher.instance.onError. - Updating UI state synchronously in a handler. This can loop on build errors. Defer the update, as
recorddoes. - Forgetting that hot reload keeps old handlers. Hot reload does not rerun
main(). After editing the installation code, use hot restart.
Exercise
In the lab, button 2 is changed to onPressed: () { Future<void>.delayed(const Duration(milliseconds: 100)).then((_) => throw StateError('x')).catchError((Object e) {}); }. Which handler, if any, receives the error, and why?
Show answer
Neither handler receives it. The Future returned by .then fails, but .catchError is attached to that same chain and consumes the error with an empty callback. The error is therefore not uncaught, so it never reaches PlatformDispatcher.instance.onError, and it was not thrown in framework-run code, so it never reaches FlutterError.onError either.
Exercise
Button 1 shows an entry with the library gesture, but your test with tester.tap expects exactly one report and sees two. List two things you would check, and what you would change in the test.
Show answer
Check whether the error was reported twice because a second handler or a wrapper also calls the sink, and check whether a framework follow-up error (for example from the same tap) added an entry. Change the test to filter the recorded entries by the exception type or message, such as asserting that at least one entry contains boom, or capture the full FlutterErrorDetails and compare details.exception instead of counting entries.
Exercise
Why does the unit test for the async handler call PlatformDispatcher.instance.onError!(...) directly instead of throwing from a failing Future inside testWidgets?
Show answer
testWidgets runs the test body in a zone that catches uncaught async errors for the test framework, so those errors do not reach PlatformDispatcher.instance.onError. Calling the callback directly tests the code you wrote: that it forwards the error to the sink and returns true.