18

I write a lot of async code that uses await to handle Futures.

If I have

() async {
  var result = await someFuture();
}

what would be the preferred way to catch errors. Wraping the code in try/catch or doing

() async {
  var result = await someFuture().catch(_errorHandler);
}

EDIT:

Also, if I have many await calls in one async method, what is the preferred catch all the errors instead of writing .catchError for eachOne.

() async {
  var result = await someFuture();
  var result2 = await someFuture2();
  var result3 = await someFuture3();

}
3
  • 1
    I suppose that when using try and catch your code would not continue executing, but continuing in the catch block after an exception is thrown. However, it will continue if you catch it like you proposed. Commented Jun 3, 2018 at 21:30
  • I edited the question for another case. Commented Jun 3, 2018 at 21:32
  • 1
    Questions that can be qualified as "Primarily opinion based" don't fit stackoverflow. As they don't have a finite answer. Commented Jun 4, 2018 at 2:58

3 Answers 3

19

According to the Dart docs if you use await wrap it in a try-catch

Sign up to request clarification or add additional context in comments.

5 Comments

Hi Thomas, I think your right, but when I look at the documentation: dart.dev/guides/libraries/futures-error-handling I don't see any example of that. Can you maybe share an example you use or to the the documentation? Just curious :)
So, a Future.error(...) within the async function will be catched by the outer try/catch?
nope, they won't
Huh? What is the point then?
you have to await the call inside a try-catch. if you have a Future.error that will receive the exception and not the try catch around it
3

The Docs suggest just wrapping in a try-catch

Example code:

try {
  print('Awaiting user order...');
  var order = await fetchUserOrder();
} catch (err) {
  print('Caught error: $err');
}

Reference also has a runnable example https://dart.dev/codelabs/async-await#handling-errors

Comments

0

The docs recommend using try-catch for error handling, just as you would in synchronous code https://dart.dev/libraries/async/async-await#handling-errors
Additionally, if you need code to execute regardless of whether an exception occurs, wrap it in finally block https://dart.dev/language/error-handling#finally

Example:

try{
  var result = await someFuture();
  var result2 = await someFuture2();
  var result3 = await someFuture3();
}catch(e){
  print('Error: $e');
}finally{
   print('Done')
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.