Is there a global handler for async Errors?

dart

Solution

You can use the brand new `Zone`s. Just run your code inside the `Zone` and attach error handler to it.

void someThirdPartyDangerousMethod() {
  new Future.value(true).then((result) => throw new Exception());
}

runZoned(() {
  // we can't use catchError, because this method does not return Future
  someThirdPartyDangerousMethod(); 
}, onError: (e) {
  logger.log(e);
});

This should just work as expected! Every uncatched error will be handled by the `onError` handler. One thing is different to the classical example with `try`-`catch` block. The code running inside the `Zone` won't stop when error occurs, error is handled by `onError` callback and the application continues.

Problem

In old-fashioned sync code, you can always assure your program won't crash completely by encapsulation your source code to the one big try catch block as in example: ``` try { // Some piece of code } catch (e) { logger.log(e); // log error } ``` However in Dart, when using `Future`s and `Stream`s, it is not so easy. Following example will crash your application completely ``` try { doSomethingAsync().then((result) => throw new Exception()); } catch (e) { logger.log(e); } ``` It doesn't matter that you have code inside the `try`-`catch` block. Yes, you can always use `Future.catchError`, unfortunately, this won't help you if you are using third-party library function as following: ``` void someThirdPartyDangerousMethod() { new Future.value(true).then((result) => throw new Exception()); } try { // we can't use catchError, because this method does not return Future someThirdPartyDangerousMethod(); } catch (e) { logger.log(e); } ``` Is there a way to prevent the untrusty code to break whole your application? Something like global error handler?

Original source