Using runZoned To Catch Unhandled Exceptions
Handling unhandled exceptions sounds convoluted, but it really isn't!
Default zone
A default zone called Zone.root
is created when executing main()
. If you don't create any custom zones (like we're going to do in a second), all code gets executed inside the default zone:
void main() {
print('Hello from the Twilight (default) Zone!');
}
Using runZoned
If you insert runZoned
into your app's main()
function, a custom zone will be created:
await runZoned<Future<void>>(() async {
...
}, onError: (Object obj, StackTrace trace) async {
// print the error to console
// send the error to crashlytics etc
});
The lambda passed as the body
argument to runZoned
will be executed in the newly created custom zone. Any exceptions that occur will bubble up to the onError
lambda.
Add runApp
to the zoned body and your whole app now captures any uncaught exceptions:
await runZoned<Future<void>>(() async {
runApp(AcmeApp());
}, onError: (Object error, StackTrace trace) async {
print(obj);
print(trace);
});
Pretty neat, huh?