Thomas
Thomas

Reputation: 181745

How to globally catch unhandled Future errors?

Best practice is of course to always attach an error handler to a Future using catchError() (or using await and try/catch). But suppose I forgot, or suppose that this error is serious enough that we want it to crash the entire application (as we could do with synchronous exceptions), or that I want to log the error, or report it to some service like Crashlytics to make me aware of my sins.

Dart's Futures are practically the same as JavaScript's Promises. In NodeJS, we can attach a handler to the global unhandledRejection event to add custom behaviour.

Does Dart offer something similar? I looked through the async and Future documentation, but couldn't find anything relevant.

Upvotes: 1

Views: 353

Answers (1)

julemand101
julemand101

Reputation: 31219

Take a look at the runZonedGuarded static method. It will executing a given method in its own Zone which makes it possible to attach a method to handle any uncaught errors.

I have made a simple example here which shows what happens if a async error are throw without any handling of the error:

import 'dart:async';
import 'dart:io';

void main() {
  runZonedGuarded(program, errorHandler);
}

Future<void> program() async {
  final file = File('missing_file.txt');
  await file.openRead().forEach(print);
}

void errorHandler(Object error, StackTrace stack) {
  print('OH NO AN ERROR: $error');
}

Which returns:

OH NO AN ERROR: FileSystemException: Cannot open file, path = 'missing_file.txt'...

Upvotes: 3

Related Questions