Skip to content

Warn when returning a function invocation when within a try block in an async function #58279

Open
@kevmoo

Description

@kevmoo

Often if you're in a try block, you want to catch exceptions.

But if you omit the await errors might flow through.

See https://dartpad.dev/c8deb87cee33b48316fc0f5cf4b1891f

Future<void> main() async {
  for (var func in [goodCatch, badCatch]) {
    print('Running $func');
    try {
      await func();
    } catch (e) {
      print('Why was this not caught? $e');
    }
    print('');
  }
}

Future<void> goodCatch() async {
  try {
    // `await` here is CRITICAL!
    return await badAsync();
  } on StateError catch (e) {
    print('Caught "$e"!');
  }
}

Future<void> badCatch() async {
  try {
    // No await, so the state error is not caught!
    return badAsync();
  } on StateError catch (e) {
    print('Caught "$e"!');
  }
}

Future<void> badAsync() async {
  throw StateError('bad!');
}
Running Closure 'goodCatch'
Caught "Bad state: bad!"!

Running Closure 'badCatch'
Why was this not caught? Bad state: bad!

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3A lower priority bug or feature requestarea-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.devexp-linterIssues with the analyzer's support for the linter packagelinter-lint-requesttype-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions