Tree
Tree

Reputation: 31361

Recommended way from dart team to catch errors when using await in Flutter

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();

}

Upvotes: 16

Views: 12668

Answers (3)

Iain Smith
Iain Smith

Reputation: 9703

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

Upvotes: 3

Shubhanshu Singh
Shubhanshu Singh

Reputation: 56

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

https://dart.dev/codelabs/async-await#handling-errors

Upvotes: 3

Thomas
Thomas

Reputation: 9257

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

Upvotes: 18

Related Questions