Sub topic 12
Pitfalls: Debug vs Release, Errors That Never Reach the Handlers, and Infinite Loops in Handlers
This chapter assumes you can already install FlutterError.onError and PlatformDispatcher.instance.onError in main(). It also assumes you know what the true or false return value of the second handler means, and that you have forwarded errors to a reporter. Here you will learn where those handlers stop working, so a working setup does not give you false confidence.
Debug and release builds behave differently
The handlers are installed the same way in every build mode. What changes is the information around them. Several things you see while developing disappear or shrink in a release build.
| Aspect | Debug build | Release build |
|---|---|---|
| Default error widget | Red screen with the exception message | Plain grey box with no message |
| Assertions | Run, and can throw | Removed, so they never throw |
| Layout overflow stripes and warnings | Shown | Not shown |
| Stack traces | Readable, with file names and lines | Unreadable if built with `--obfuscate` or `--split-debug-info` |
| Console output | Verbose | Do not rely on it |
Three consequences follow from this table.
- Some errors only exist in debug. An
assertthat fails in debug is silently skipped in release. A clean release run does not prove the code is free of the problems that debug reported. - Stack traces need symbols. If you build with
--obfuscate --split-debug-info=<dir>, the traces your handler forwards are mangled. Keep the symbol files from each build and give them to your crash-reporting service, or the reports are hard to use. - The grey box is a user-facing screen. If you set
ErrorWidget.builder, test it in a release build too. The red screen you replaced was only ever visible to developers.
A common mistake is sending every debug-time error to the production crash service. Gate the reporting with kReleaseMode or kDebugMode from package:flutter/foundation.dart, and keep printing locally in debug.
Errors that never reach the handlers
Both global handlers cover a lot, but not everything. This diagram shows where an error goes depending on where it was thrown.
Errors you already caught
If your own try/catch or catchError handles an error, the global handlers never see it. That is correct behavior, but it means a catch block that only prints, or is empty, hides a failure from your reporter. When you catch something you cannot recover from, report it yourself or rethrow it.
import 'package:flutter/foundation.dart';
Future<void> loadProfile(Future<String> Function() fetch) async {
try {
await fetch();
} catch (error, stack) {
// Caught here, so neither global handler will ever see it.
debugPrint('loadProfile failed: $error\n$stack');
rethrow; // Let it reach PlatformDispatcher.onError as well.
}
}Errors in other isolates
Each isolate has its own event loop. An uncaught error inside a worker created with Isolate.spawn does not travel to PlatformDispatcher.instance.onError on the main isolate. You must listen for it explicitly. The onError parameter of Isolate.spawn sends each error to a port as a two-item list, an error string and a stack trace string.
import 'dart:isolate';
import 'package:flutter/foundation.dart';
void worker(Object? message) {
throw StateError('worker failed');
}
Future<void> startWorker() async {
final errors = RawReceivePort((dynamic pair) {
final list = pair as List<dynamic>;
debugPrint('worker error: ${list.first}\n${list.last}');
});
await Isolate.spawn(worker, null, onError: errors.sendPort);
// Call errors.close() when the worker is finished, or the port keeps
// the isolate listening.
}Isolate.run and compute behave differently. They return a Future, and a failure inside the worker is delivered as an error on that future. If you await it inside try/catch, you catch it. If you ignore the future, the error becomes an uncaught async error on the main isolate, and PlatformDispatcher.onError receives it.
Native crashes
FlutterError.onError and PlatformDispatcher.onError handle Dart exceptions. A crash in Kotlin, Swift, Objective-C, or C++ code, such as a null pointer in a plugin or an out-of-memory kill, is not a Dart exception. Neither handler runs. Real production coverage needs a crash-reporting SDK that also installs native handlers, and the Dart handlers feed it the Dart-side errors.
Errors before the handlers exist
An error thrown in main() before you assign the handlers goes to the defaults. Put the handler assignments at the very top of main(), directly after WidgetsFlutterBinding.ensureInitialized(), and before any await. Do any slow initialization, such as opening a database or loading config, after that point.
Errors from a different zone
Code wrapped in runZonedGuarded sends uncaught async errors to that zone's own error handler instead of PlatformDispatcher.onError. If you inherited an app that still uses runZonedGuarded, you may have two competing paths. Another problem is a zone mismatch: calling WidgetsFlutterBinding.ensureInitialized() in one zone and runApp in another. Flutter prints a warning when it detects this. If you keep a zone, initialize the binding and call runApp inside the same zone. For new code, prefer the two handlers from this tutorial and remove the zone.
Handlers that cause infinite loops
A global handler is code that runs when something has already gone wrong. If it fails the same way, it can produce a new error that arrives at the same handler. That loop can freeze the app or flood your reporting service.
These are the common causes.
- An unawaited reporting call that fails. The handler calls an async
send()and does not handle its failure. When the network is down, the future fails with no listener, that uncaught async error reachesPlatformDispatcher.onError, the handler callssend()again, and so on. - A handler that throws synchronously. A bad cast, a null check, or a missing plugin inside
FlutterError.onErrorcreates a second error while you are handling the first. - A handler that touches the UI. Calling
setStateor showing a dialog from a handler can trigger another build that throws the same exception again. - A build error that repeats every frame. A widget whose
buildthrows is rebuilt whenever its parent is. The framework reports the error each time, so one bug can produce hundreds of reports per second.
To defend against all four, make the handler small, wrap its work in try/catch, attach catchError to any future it starts, and rate-limit repeats. This version does all of them.
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
final Map<String, DateTime> _lastSent = <String, DateTime>{};
bool _inHandler = false;
Future<void> _sendToService(String message, StackTrace? stack) async {
// Replace with a real network call. It is allowed to fail.
await Future<void>.delayed(const Duration(milliseconds: 10));
}
void safeReport(Object error, StackTrace? stack) {
if (_inHandler) return; // Stop synchronous re-entry.
_inHandler = true;
try {
final firstLine = stack?.toString().split('\n').first ?? '';
final key = '${error.runtimeType}:$firstLine';
final now = DateTime.now();
final last = _lastSent[key];
if (last != null && now.difference(last) < const Duration(seconds: 10)) {
return; // Same error seen recently, skip it.
}
_lastSent[key] = now;
_sendToService(error.toString(), stack).catchError((Object e) {
// A failed report must never become a new uncaught error.
debugPrint('Reporting failed: $e');
});
} catch (e) {
debugPrint('Handler failed: $e');
} finally {
_inHandler = false;
}
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details);
if (kReleaseMode) safeReport(details.exception, details.stack);
};
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
if (kReleaseMode) safeReport(error, stack);
return true;
};
runApp(const MaterialApp(home: Scaffold(body: Center(child: Text('Hello')))));
}The _inHandler flag stops synchronous recursion only. It cannot guard the asynchronous part, because the finally block runs as soon as the future starts. The catchError call is what protects against the asynchronous loop. The time-based map is a crude rate limiter, and a production reporting SDK usually does this better.
Smaller limits worth remembering
- Returning
truehides the error. OncePlatformDispatcher.onErrorreturnstrue, the default report is suppressed. If your reporter is a stub, you now have an app that fails silently. Returnfalsefor errors you decide not to handle. - The app may be in a bad state. An uncaught async error often means an operation stopped halfway, such as a form that never finished saving. Reporting it does not repair that state.
- Tests replace the handlers.
flutter_testinstalls its ownFlutterError.onErrorto fail tests on errors. Do not expect your production handlers to run in widget tests. ErrorWidget.builderruns during build. Keep it free of network calls, state changes, and anything that can throw.
Checklist before shipping
- Handlers are assigned right after
ensureInitialized()and before anyawait. - Both handlers wrap their work in
try/catchand handle failures of any future they start. - Repeated errors are rate-limited or deduplicated.
- Debug errors are kept out of the production crash service.
- Symbol files are saved for every obfuscated release build.
- Isolates you spawn have an error port or an awaited future.
- A native crash reporter is in place if you need coverage beyond Dart.
- A release build, not only a debug build, shows the error screen you expect.
Exercise
Your PlatformDispatcher.instance.onError handler calls sendReport(error), an async function that does a network request, without await or catchError. With the phone in airplane mode, the app's CPU usage climbs and the console fills with repeated errors. Explain why this happens and give two changes that fix it.
Show answer
With no network, the future returned by sendReport fails and nobody listens to it. A failed future with no listener is an uncaught async error, so it reaches PlatformDispatcher.instance.onError. The handler calls sendReport again, which fails again, and the cycle repeats. Fixes: attach .catchError(...) (or use try/catch around an awaited call) so a failed report is handled locally, and rate-limit or deduplicate reports so the same error is not sent repeatedly. A re-entrancy flag covers synchronous recursion only.
Exercise
A background worker started with Isolate.spawn throws an exception, but your PlatformDispatcher.instance.onError handler never logs it. Why, and how do you receive the error?
Show answer
Each isolate has its own event loop, and an uncaught error in a spawned isolate is not delivered to the main isolate's PlatformDispatcher.instance.onError. Pass a SendPort as the onError argument to Isolate.spawn (or call addErrorListener) and read the two-item list of error string and stack trace string from a RawReceivePort. With Isolate.run or compute, await the returned future inside try/catch instead.
Exercise
Your release build's crash reports contain stack traces like package:app/main.dart replaced by short meaningless symbols. What most likely caused this, and what should you keep from each build?
Show answer
The app was built with --obfuscate and --split-debug-info, which mangles names in stack traces. Keep the symbol files written to the --split-debug-info directory for every released build, and upload them to the crash-reporting service so it can translate the traces.