Sub topic 3
Handling framework errors with FlutterError.onError
This chapter explains what FlutterError.onError receives, how to install a handler, and how to read the error details it gives you. It assumes you know basic Dart syntax (including async/await and Future), have built a small Flutter app with runApp, and are comfortable with try/catch. Errors that escape the framework's own catching are covered in other chapters. They are mentioned here only to mark the boundary.
What the framework catches
Flutter does not let one bad widget kill the app. The framework wraps the code it calls on your behalf in try/catch blocks. When that code throws, the framework packages the exception and passes it to FlutterError.onError.
The framework catches exceptions thrown during these phases:
- Build. Your
buildmethod,initState,didChangeDependencies, and similar widget lifecycle methods. - Layout.
performLayoutand related methods in render objects. - Paint.
paintmethods in render objects. - Gesture callbacks. Synchronous code in callbacks such as
onPressedoronTap. The gesture system runs these inside its owntry/catch. - Scheduler callbacks. Frame callbacks and post-frame callbacks.
- Image and asset loading failures that the framework reports itself.
The rule of thumb is that the framework catches an error when the framework is the caller on the stack. It cannot catch an error that is thrown later, after the callback has already returned. A Future that fails after an await in an onPressed callback is one example. That error belongs to PlatformDispatcher.instance.onError, which is a separate channel.
Installing the handler
FlutterError.onError is a static field of type FlutterExceptionHandler?. That type is a function that takes a FlutterErrorDetails and returns nothing. Assign your own function to replace the default behavior.
Install the handler in main(), before runApp. Call WidgetsFlutterBinding.ensureInitialized() first so the binding exists before you touch framework state:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
debugPrint('Framework error: ${details.exceptionAsString()}');
};
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(body: Center(child: Text('Hello'))),
);
}
}The default value of FlutterError.onError prints a formatted report to the console. When you assign your own function, the default is gone. Nothing prints unless your handler prints it. That is why the example calls FlutterError.presentError(details). It runs the standard presentation, so you still see the familiar console output while you add your own behavior.
The handler runs in every build mode: debug, profile and release. The framework calls it whenever it catches an error. Later chapters cover the differences between modes in more detail.
Reading FlutterErrorDetails
The handler receives a FlutterErrorDetails object. These are the members you use most:
| Member | Type | Meaning |
|---|---|---|
| `exception` | `Object` | The thrown object. It is not always an `Exception`. Dart allows throwing any object. |
| `stack` | `StackTrace?` | The stack trace at the throw site. It can be null. |
| `library` | `String?` | A short name for the part of Flutter that caught the error, such as `widgets library` or `rendering library`. |
| `context` | `DiagnosticsNode?` | A description of what the framework was doing, such as "building MyWidget". |
| `informationCollector` | function or null | Produces extra diagnostic text, such as the widget ancestor chain. |
| `silent` | `bool` | True when the error is expected to be hidden from the user, but still reported. |
| `exceptionAsString()` | method | A readable string for the exception, with extra detail for `FlutterError` objects. |
exception is typed as Object, so do not cast it to Exception or Error without checking. Use exceptionAsString() for a message, or exception.runtimeType when you want to group errors by type.
silent matters when you forward errors. Some errors, such as failures to load an image that is optional, are marked silent. The default handler skips printing them in some situations. Decide deliberately whether your reporter should receive them.
presentError and the console
FlutterError.presentError is the function that formats and prints the error. You call it from your handler to keep the default console output. You can skip it in a release build, where console output is not useful to anyone. A common arrangement prints in debug mode and reports in release mode:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void sendToReportingService(Object error, StackTrace? stack, {String? reason}) {
// Replace this with a call to your crash-reporting SDK.
debugPrint('report: $error (${reason ?? 'no reason'})');
if (stack != null) {
debugPrint('$stack');
}
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails details) {
if (kDebugMode) {
FlutterError.presentError(details);
}
sendToReportingService(
details.exception,
details.stack,
reason: details.library,
);
};
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(body: Center(child: Text('Hello'))),
);
}
}Keeping the forwarding code in one function means you can change the reporting service without touching how the handler is installed.
Chaining to an existing handler
Another package may already have installed a handler. Crash-reporting SDKs commonly do this during their own setup. If you overwrite FlutterError.onError, you remove their handler. To avoid that, save the previous value and call it from your handler:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void installFrameworkErrorHandler() {
final FlutterExceptionHandler? previous = FlutterError.onError;
FlutterError.onError = (FlutterErrorDetails details) {
// Your own logic first.
debugPrint('Framework error in ${details.library}: '
'${details.exceptionAsString()}');
// Then whatever was installed before, or the default presentation.
if (previous != null) {
previous(details);
} else {
FlutterError.presentError(details);
}
};
}Note the order of setup. If an SDK installs its handler after yours, it should do the same chaining, and the order of the two installs decides which one runs first. When you add a reporting SDK, read its setup instructions and check whether it replaces or wraps FlutterError.onError.
Triggering an error to see it work
You can confirm the handler works by throwing from a callback the framework runs. A synchronous throw inside onPressed goes through the gesture system, so it reaches FlutterError.onError:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
debugPrint('HANDLER CALLED: ${details.exceptionAsString()}');
};
runApp(const MaterialApp(home: Scaffold(body: SyncErrorButton())));
}
class SyncErrorButton extends StatelessWidget {
const SyncErrorButton({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () => throw Exception('Synchronous error in onPressed'),
child: const Text('Throw sync error'),
),
);
}
}Run the app and tap the button. The console shows the standard report from presentError, followed by the line starting with HANDLER CALLED. The app keeps running. The framework caught the exception, so the gesture system is intact and you can tap again.
A second way to check is to throw from build. The handler is called, and the widget that threw is replaced on screen by an error widget. A red screen appears in debug mode and a grey box in release mode. Customizing that widget is a separate topic.
What the handler cannot do
FlutterError.onError is a notification channel. It tells you an error occurred after the framework has already dealt with it. Some limits follow from that:
- It does not stop the error. The framework has already caught it and continues. You cannot "resume" the failed build, and the affected widget is replaced with an error widget.
- It does not see asynchronous failures. An
awaitthat throws after a callback returns bypasses it. This is the job ofPlatformDispatcher.instance.onError. - It does not see errors you catch yourself. If your code wraps a call in
try/catchand swallows the exception, neither handler runs. You can report it explicitly withFlutterError.reportError, which builds aFlutterErrorDetailsand calls the currentonError.
FlutterError.reportError is useful for errors you handle but still want counted:
import 'package:flutter/foundation.dart';
Future<void> loadProfile() async {
try {
await Future<void>.delayed(const Duration(milliseconds: 50));
throw const FormatException('Bad profile data');
} catch (error, stack) {
FlutterError.reportError(
FlutterErrorDetails(
exception: error,
stack: stack,
library: 'profile loader',
context: ErrorDescription('while loading the profile'),
),
);
// Continue with a fallback here.
}
}This sends a handled error through the same pipeline as framework errors, so it reaches the same reporter and the same console output.
Writing a safe handler
Your handler runs while the framework is in the middle of reporting a failure. Keep it simple:
- Do not throw from it. An exception inside the handler has nowhere good to go. Wrap risky reporting calls in
try/catch. - Do not call
FlutterError.reportErrororFlutterError.onErrorfrom inside the handler. That calls the handler again, and the recursion can loop forever if the cause persists. - Do not start long synchronous work. The handler may run during a frame. Heavy work there can cause dropped frames. Send the data off and return.
- Do not call
setStateor show dialogs directly. The error may have happened while the widget tree was being built, when changing it is not allowed.
Summary of the working model
- The framework calls your code inside
try/catchfor build, layout, paint, gesture, and scheduler work. - When something throws, the framework builds a
FlutterErrorDetailsand callsFlutterError.reportError, which callsFlutterError.onError. - Your handler decides what to do. Call
FlutterError.presentErrorto keep console output, and forward the details to a reporting service. - The app continues. The failed widget is replaced by an error widget.
- Errors outside this path, such as failed
Futures with no listener, need a second handler.
Exercise
A button's onPressed is written as onPressed: () async { await Future<void>.delayed(const Duration(milliseconds: 100)); throw StateError('late'); }. Will FlutterError.onError receive this error? Explain, and say what you would use to receive it.
Show answer
No. The framework only catches what is thrown while it is the caller on the stack. The async callback returns a Future immediately, so the gesture system's try/catch has already finished. The StateError is thrown later inside the Future, which then fails with no listener. That uncaught asynchronous error is reported to PlatformDispatcher.instance.onError, so you would install a handler there. A synchronous throw such as onPressed: () => throw StateError('now') would reach FlutterError.onError.
Exercise
Your handler is FlutterError.onError = (details) { debugPrint(details.exceptionAsString()); };. After you add it, the usual red console report no longer appears when a widget fails. Why, and how do you restore it?
Show answer
Assigning FlutterError.onError replaces the default handler, which was responsible for printing the report. Call FlutterError.presentError(details) inside your handler (or call the previous handler you saved before assigning) to keep the standard console output.