dart-lang / site-www

Source for Dart website
https://dart.dev
Other
943 stars 683 forks source link

Effective dart code example for async/await guideline doesn't follow the guideline about catching exceptions. #3132

Open tetkin-g opened 3 years ago

tetkin-g commented 3 years ago

In Effective Dart, the guideline about preferring async/await over raw futures includes this as an example of good code:

Future<int> countActivePlayers(String teamName) async {
  try {
    var team = await downloadTeam(teamName);
    if (team == null) return 0;

    var players = await team.roster;
    return players.where((player) => player.isActive).length;
  } catch (e) { // <----
    log.error(e);
    return 0;
  }
}

However it violates the guideline about catches without on clauses.

munificent commented 3 years ago

Good catch. We can fix this by having the example catch some fictitious type that downloadTeam() would theoretically throw, like:

Future<int> countActivePlayers(String teamName) async {
  try {
    var team = await downloadTeam(teamName);
    if (team == null) return 0;

    var players = await team.roster;
    return players.where((player) => player.isActive).length;
  } on DownloadException catch (e) { // <----
    log.error(e);
    return 0;
  }
}