Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Exceptions up the stack in Dart from async to sync methods

So, coming from Javascript world, I can handle exceptions that are thrown however deep down the stack. Doing the same in Dart doesn't work. I'm not sure how to pass exceptions up, to be handled at the root of the stack.

willThrow() async {
    throw Exception('Im an exception');
}

init() async {
    final illNeverExist = await willThrow();
    print(illNeverExist);
}

main() {
  try {
    init();
  } catch(err) {
    print(err);
  }
}

^^^ This totally works in javascript.

In 'init', even if I wrap that in a try catch, and throw that error, I always get an uncaught exception.

init() async {
    try {
        final illNeverExist = await willThrow();
        print(illNeverExist);
    } catch(err) {
        throw err
    }
}

How do you pass async exceptions up the stack in dart?!

like image 642
Anthony Urbina Avatar asked Dec 07 '25 10:12

Anthony Urbina


1 Answers

The try-catch block in your main function doesn't wait for your asynchronous init function to complete. Consequently, when init does complete, its exception will no longer be caught.

You can fix this by making main async and using await init();, or you can use Future.catchError to directly register an error callback on the returned Future.

like image 114
jamesdlin Avatar answered Dec 11 '25 21:12

jamesdlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!