Sub topic 7
Sending Errors to a Logging or Crash-Reporting Service
This chapter assumes you have already installed FlutterError.onError and PlatformDispatcher.instance.onError in main(), and that you know what each one receives. Here you build the part that was a debugPrint placeholder until now: sending those errors somewhere you can read them after the app has shipped.
Why printing is not enough
debugPrint writes to the console of the machine running your app. Once the app is on a user's phone, nobody sees that console. If you want to know about crashes in production, each uncaught error has to leave the device and reach a service you control or a hosted crash-reporting product.
Forwarding errors raises four design questions:
- The two handlers receive different shapes of data. How do you turn them into one report?
- How do you keep the reporting code from causing new errors?
- How do you avoid flooding the service with thousands of copies of the same error?
- Which errors should leave the device at all, for example in debug builds?
Two shapes, one report
The two handlers hand you different objects.
| Row | `FlutterError.onError` | `PlatformDispatcher.instance.onError` |
|---|---|---|
| Receives | One `FlutterErrorDetails` | An `Object error` and a `StackTrace` |
| Stack trace | `details.stack`, which may be `null` | Always present, though it can be empty |
| Extra context | `library`, `context`, `silent`, `informationCollector` | None |
| Return value | None (`void`) | `bool`, where `true` means handled |
| Typical severity | App usually keeps running | Nothing caught it, so treat it as fatal |
The extra context in FlutterErrorDetails is useful when you triage. details.library names the part of Flutter that caught the error, such as widgets library or rendering library. details.exceptionAsString() gives a readable message. details.exception is the original object, which can be any Object and is not always an Exception.
The simplest way to cope with two shapes is to convert both into a single ErrorReport class. Everything after that point, such as deduplication, filtering and sending, works on one type.
A reporter you can swap sinks on
The next example is a complete app file. It has three parts:
ErrorReportis the normalized data.ErrorSinkis the destination. It is an interface, so the app does not depend on one vendor.ErrorReporterconverts both error shapes into reports, drops duplicates, and never throws.
import 'dart:async';
import 'dart:convert';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class ErrorReport {
ErrorReport({
required this.error,
required this.stack,
required this.source,
this.library,
this.fatal = false,
}) : timestamp = DateTime.now().toUtc();
final Object error;
final StackTrace stack;
final String source; // 'framework' or 'async'
final String? library;
final bool fatal;
final DateTime timestamp;
Map<String, Object?> toJson() => {
'type': error.runtimeType.toString(),
'message': error.toString(),
'stack': stack.toString(),
'source': source,
'library': library,
'fatal': fatal,
'timestamp': timestamp.toIso8601String(),
};
}
abstract class ErrorSink {
Future<void> send(ErrorReport report);
}
class ConsoleSink implements ErrorSink {
@override
Future<void> send(ErrorReport report) async {
debugPrint(jsonEncode(report.toJson()));
}
}
class ErrorReporter {
ErrorReporter(this._sink, {this.dedupeWindow = const Duration(seconds: 30)});
final ErrorSink _sink;
final Duration dedupeWindow;
final Map<String, DateTime> _lastSeen = {};
void reportFlutterError(FlutterErrorDetails details) {
_submit(ErrorReport(
error: details.exception,
stack: details.stack ?? StackTrace.current,
source: 'framework',
library: details.library,
));
}
bool reportAsyncError(Object error, StackTrace stack) {
_submit(ErrorReport(
error: error,
stack: stack,
source: 'async',
fatal: true,
));
return true;
}
void _submit(ErrorReport report) {
try {
final now = DateTime.now();
final firstFrame = report.stack.toString().split('\n').first;
final key = '${report.error.runtimeType}|$firstFrame';
final last = _lastSeen[key];
if (last != null && now.difference(last) < dedupeWindow) return;
_lastSeen[key] = now;
if (_lastSeen.length > 100) {
_lastSeen.removeWhere((_, seen) => now.difference(seen) >= dedupeWindow);
}
unawaited(
_sink.send(report).catchError((Object e) {
debugPrint('Error report failed to send: $e');
}),
);
} catch (e) {
debugPrint('Error reporter failed: $e');
}
}
}
void installErrorHandlers(ErrorReporter reporter) {
FlutterError.onError = (FlutterErrorDetails details) {
FlutterError.presentError(details); // console output first
reporter.reportFlutterError(details);
};
PlatformDispatcher.instance.onError = reporter.reportAsyncError;
}
void main() {
WidgetsFlutterBinding.ensureInitialized();
installErrorHandlers(ErrorReporter(ConsoleSink()));
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () async {
await Future<void>.delayed(const Duration(milliseconds: 100));
throw StateError('Async failure for the reporter');
},
child: const Text('Throw async error'),
),
),
),
);
}
}Run it and press the button. The async StateError reaches reportAsyncError, and you see one JSON line in the console. Press it again within 30 seconds and nothing new is printed, because the deduplication key matches.
Why the reporter looks defensive
Several choices in ErrorReporter guard against failures in the reporting path itself:
- Everything is wrapped in
try/catch. If the reporter throws insideFlutterError.onError, that new error is itself an uncaught error. In the worst case it re-enters the same handler and loops. The pitfalls chapter covers this in detail. sendis not awaited. Both handlers are synchronous, so you cannot wait for the network there.unawaitedmakes the fire-and-forget intent explicit, andcatchErrorstops a failed request from becoming yet another uncaught async error.- Console output comes first.
presentErrorruns before the reporter, so developers still see the error if reporting breaks. - Duplicates are dropped. A widget that throws during
buildcan throw again on every frame, so one bug may produce hundreds of identical errors per second. The deduplication window keeps one report per key per 30 seconds. The pruning line stops the map from growing without limit.
Sending to a real endpoint
To send over HTTP, add a second ErrorSink. This one uses package:http (flutter pub add http), which works on mobile, desktop and web. The endpoint is a placeholder.
import 'dart:convert';
import 'package:http/http.dart' as http;
class HttpSink implements ErrorSink {
HttpSink(this.endpoint, {http.Client? client})
: _client = client ?? http.Client();
final Uri endpoint;
final http.Client _client;
@override
Future<void> send(ErrorReport report) async {
await _client
.post(
endpoint,
headers: {'content-type': 'application/json'},
body: jsonEncode(report.toJson()),
)
.timeout(const Duration(seconds: 10));
}
}Place this class in the same library as ErrorSink and ErrorReport, or import them. Choose the sink once in main():
final sink = kReleaseMode
? HttpSink(Uri.parse('https://errors.example.com/v1/reports'))
: ConsoleSink();
installErrorHandlers(ErrorReporter(sink));This sends only release-build errors to the network. Debug errors stay on your screen. This also keeps your crash dashboard free of errors from half-finished work.
A production-grade sink would also queue reports while the device is offline and retry them later. Keep that queue bounded. An unbounded list of stack traces in memory is a leak. Hosted SDKs already do this work, which is a strong reason to use one.
Using a hosted crash-reporting SDK
With a hosted service, the ErrorSink is the SDK. For Firebase Crashlytics, the handlers call the SDK directly. This snippet assumes your project is already configured with firebase_core and firebase_crashlytics:
import 'dart:ui';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/material.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
return true;
};
runApp(const MaterialApp(home: Scaffold(body: Center(child: Text('Hello')))));
}The pattern matches what you built: one assignment per handler, and true returned for async errors. The SDK does the normalizing, grouping and offline queueing. The fatal flag marks the report as a crash instead of a logged problem.
Other SDKs follow the same pattern, but some install the handlers for you inside their own init function. If you assign FlutterError.onError after such an init call, you replace the SDK's handler and its reports silently stop. Read the vendor's setup guide and keep only one owner for each handler.
Chaining instead of replacing
If another library has already set a handler and you want both to run, save the previous value and call it:
void installChainedHandlers(ErrorReporter reporter) {
final previousFlutterHandler = FlutterError.onError;
FlutterError.onError = (FlutterErrorDetails details) {
previousFlutterHandler?.call(details);
reporter.reportFlutterError(details);
};
final previousAsyncHandler = PlatformDispatcher.instance.onError;
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
final previousHandled = previousAsyncHandler?.call(error, stack) ?? false;
final ourHandled = reporter.reportAsyncError(error, stack);
return previousHandled || ourHandled;
};
}FlutterError.onError is a nullable void Function(FlutterErrorDetails)?, and the default value already prints errors to the console. If you chain to it and also call presentError, you will see each error printed twice. Pick one.
Deciding what to send
Not everything the handlers receive deserves a report.
- Release versus debug. Gate on
kReleaseModeas shown, or on a build flavor. Some teams also send from profile or staging builds so they can test the pipeline. - Silent errors.
details.silentistruefor errors Flutter chooses not to print, such as some image-loading failures. Reporting them is a choice. Skipping them lowers noise, and including them can reveal real problems like broken image URLs. - Personal data. Exception messages often contain user input, such as an email address inside a
FormatException. Stack traces and messages are uploaded as written. Redact or avoid sensitive values before they get into an error message, and check the privacy rules that apply to your app. - Context. A report is easier to act on with the app version, platform, and a user or session id that is not personally identifying. Add these fields to
ErrorReport.toJsonso every report carries them.
Edge cases to keep in mind
- Empty stacks. An async error can arrive with
StackTrace.empty. Your deduplication key then falls back to the error type alone, so different bugs of the same type within the window will merge. Includeerror.toString()in the key if that matters to you. - Errors during startup. Handlers do nothing for errors thrown before you install them. Install them directly after
WidgetsFlutterBinding.ensureInitialized(), before any other initialization that can fail. - Handler runs on the main isolate. A slow synchronous step, such as building a large JSON string for a huge stack trace, delays frames. Keep the synchronous part short and push the rest to the sink.
- Reports can be lost. If the process dies before the HTTP request completes, the report is gone. Hosted SDKs write reports to disk first and upload on the next launch. A hand-built sink does not, unless you add that.
Exercise
In the ErrorReporter above, why is the result of _sink.send(report) wrapped in unawaited(...) with catchError, instead of being awaited inside the handler?
Show answer
Both handlers are synchronous callbacks, so they cannot wait for a network request. unawaited states that the request is fire-and-forget on purpose. catchError handles a failed request, such as a timeout or no connection. Without it, the failed Future would become a new uncaught async error and arrive in PlatformDispatcher.instance.onError, which would call the reporter again.
Exercise
Your app starts showing the same build error 60 times per second, and your crash dashboard fills up. Which part of the reporter prevents this, and how does it decide two errors are the same?
Show answer
The deduplication in ErrorReporter._submit. It builds a key from the error's runtime type and the first line of its stack trace. If the same key was seen within dedupeWindow (30 seconds by default), the report is dropped. After the window passes, the same error is reported again.
Exercise
You add a hosted SDK whose init function installs its own FlutterError.onError. Then your main() assigns FlutterError.onError = myHandler afterwards. What goes wrong, and how do you fix it?
Show answer
Assigning replaces the SDK's handler, so the SDK stops receiving framework errors. Fix it by saving the previous value (final previous = FlutterError.onError;) and calling previous?.call(details) inside your handler, or by letting only one of them own the handler and forwarding to the other from there.