Skip to content

Linter rule to prevent returning futures from the try block #62555

Open

Description

@DaniilAlpha

There have been multiple times when I’ve accidentally written code like this:

Future<Foo> doSomethingUsefulAndGetFoo() async {
  try {
    /* do something useful */
    return getFooButMayFail(); // wrong!
  } on GettingFooFailedException {
    /* do something with the exception */
    rethrow;
  }
}

While the right code would look like so:

Future<Foo> doSomethingUsefulAndGetFoo() async {
  try {
    /* do something useful */
    return await getFooButMayFail();
  } on GettingFooFailedException {
    /* do something with the exception */
    rethrow;
  }
}

The problem can be somewhat hard to spot: we are returning a Future<Foo> from the function instead of awaiting it and returning the result. In the first case, the exception does not reach the catch block, causing it to be thrown outside without the intended handling. Even when the goal is only to catch and not rethrow, this remains an issue—and I can’t recall ever writing this intentionally.

I thought it would be great if there were a linter rule for this, but since there isn’t, I’m submitting this feature request.

Activity

  1. added
    area-devexpFor issues related to the analysis server, IDE support, linter, `dart fix`, and diagnostic messages.
    on Jan 30, 2026
  2. changed the title [-]Linter rule to prevent returning futures from the try/catch block[/-] [+]Linter rule to prevent returning futures from the try block[/+] on Jan 30, 2026
  3. FMorschel commented on Jan 31, 2026

    @FMorschel
    Contributor

    I love this idea!

    And I would actually prefer if we had the exact opposite of unnecessary_await_in_return (if the body is async we suggest people to add the await). I think there was a language issue around that (IIRC @lrhn was part of the discussion or the author), but I can't find it.

    It is currently hard to find where an async error comes from (see #62448 and related) so this would definitely help with this.

    I'd be willing to implement this if the team agrees. Otherwise, I'll probably do it myself on my plugin anyway.

    CC @bwilkerson @srawlins

  4. FMorschel commented on Feb 2, 2026

    @FMorschel
    Contributor
  5. eernstg commented on Feb 2, 2026

    @eernstg
    Member

    The behavior as described in the OP is actually a bug (see #44395). The exception should be thrown during the execution of the return statement, and the catch block should run. In other words, the behavior should be the same as in the variant that includes an await.

    The proposal in dart-lang/language#870 would make the code with the buggy behavior a compile-time error, and the proposed lint would make it a less severe diagnostic. Another alternative would be to make it a warning, such that the wrong behavior is flagged even for developers who haven't enabled the lint (and, perhaps, are not aware of the issue). All of those approaches would allow us to eliminate code that triggers this bug, but it is of course also an option to fix the bug in the first place. ;-)

    Nevertheless, dart-lang/language#870 is quite likely to be implemented because it allows the context type for return statements in async functions to be simpler, which will presumably make the resulting code easier to read and maintain. Also, fixing the bug gives rise to some hard-to-find bugs in existing code—we tried it and then reverted the fix...

    @bwilkerson, @srawlins, @scheglov, WDYT? Would you consider adding a warning for the known-buggy case? That is, a return statement return e; that occurs inside a try block in a function body which is marked async such that the static type of e is a subtype of Future<T> where T is the future value type of the nearest enclosing function.

    This approach has false negatives; in particular, the static type of e could be dynamic, which is not flagged, but may still give rise to the buggy behavior. On the other hand, it does not have false positives; every case which is flagged will give rise to the buggy behavior if the evaluation of e yields a future which is completed with an error.

  6. FMorschel commented on Feb 2, 2026

    @FMorschel
    Contributor

    Oh, so this is basically a duplicate of (with a different name but basically the same idea):

    Found it at #44395.

  7. eernstg commented on Feb 2, 2026

    @eernstg
    Member

    Right, I forgot about that one!

  8. FMorschel commented on Feb 2, 2026

    @FMorschel
    Contributor

    And as mentioned in this comment from @natebosch:

    You shouldn't use unnecessary_await_in_return at all. I think we should probably remove that lint.

    I strongly agree with this.

  9. bwilkerson commented on Feb 2, 2026

    @bwilkerson
    Member

    Would you consider adding a warning for the known-buggy case?

    I have no objection to adding a warning with no false positives.

    And I have no objection to removing the lint.

  10. FMorschel commented on Feb 2, 2026

    @FMorschel
    Contributor

    I've made the new rule on this CL https://dart-review.googlesource.com/c/sdk/+/477660.

    After it lands, I plan on making a new one for removing unnecessary_await_in_return.

  11. eernstg commented on Feb 3, 2026

    @eernstg
    Member

    Sounds good!

    However, it's worth noting that the 'no false positives' property only holds if the extra conditions are taken into account. In particular, if we want the breakage to be minimal, the diagnostic message should only be emitted for return statements that occur inside a try block.

  12. srawlins commented on Feb 4, 2026

    @srawlins
    Member

    I don't want to scope-creep this 😅 but should this also consider yield Future.value(7);?

    (Note: It can be harder to incrementally report more cases with a warning or lint rule, than just tackling them in one swoop, making reviewers look at cleanup CLs in one go.)

  13. srawlins commented on Feb 4, 2026

    @srawlins
    Member

    Oh also (I'd prefer to have the discussion here rather than on the CL; forgive me if this is addressed in the CL already), do we report the following cases:

    • return e; where the static type of e is FutureOr<whatever>
    • return e; where the static type of e is a type variable, T, with bound Future<something>, or bound FutureOr<something>
    • return e; where the static type of e is a subtype (or assignable to?) Future<something>; this would be like various Future subtypes that are around like SyncFuture I think, and CancellableFuture.
  14. FMorschel commented on Feb 4, 2026

    @FMorschel
    Contributor

    [S]hould this also consider yield Future.value(7);?

    I'd say so. I can't see any reason not to, but I'll leave it up for the team to answer for certain.

    [D]o we report the following cases:

    * `return e;` where the static type of `e` is `FutureOr<whatever>`
    

    Yes.

    * `return e;` where the static type of `e` is a type variable, `T`, with bound `Future<something>`, or bound `FutureOr<something>`
    

    I think it should, but I'll be sure to add a test case.

    * `return e;` where the static type of `e` is a subtype (or assignable to?) `Future<something>`; this would be like various Future subtypes that are around like `SyncFuture` I think, and `CancellableFuture`.
    

    This one, I'm pretty certain it should, but again, I'll add another test case.

    Thanks!

  15. FMorschel commented on Feb 4, 2026

    @FMorschel
    Contributor

    Another question I raised at the CL (if you prefer to discuss it over here) is:

    Should this be a lint or a warning (or both)?

    I'm in favour of adding both and sharing the same visitor. The key difference would be that the warning would look for cases like this only inside try blocks (to avoid the bug in question here), and the lint would trigger all return (maybe yield) occurrences (aiming to push dart-lang/language#870).

    I can make separate CLs; I just want to know what our goal is.

  16. 51 remaining items

  17. FMorschel commented on Jun 8, 2026

    @FMorschel
    Contributor

    Thanks, @eernstg!

    That is what I thought.

    But now, if we consider the non-try cases. Should we add the fix to those? Since removing the async wouldn't make any difference to those.

    Future<int> bar() => 0;
    
    Future<void> foo() async {
      return bar();
    }
    
    void main() async {
      print('Starting!');
      await foo();
      print('Done!');
    }

    This would be adding the fix to the lint (async_return_with_no_await - consider its goal as a hint towards dart-lang/language#870) and not the analyzer warning (unawaited_return_in_try_block).

  18. FMorschel commented on Jun 26, 2026

    @FMorschel
    Contributor
  19. FMorschel commented on Jul 2, 2026

    @FMorschel
    Contributor
  20. FMorschel commented on Jul 2, 2026

    @FMorschel
    Contributor

    I've also opened:

    So we can discuss that fix over there. This way, once the CL above lands, this issue will be closed.

  21. FMorschel commented on Jul 14, 2026

    @FMorschel
    Contributor

    @srawlins wrote at https://dart-review.googlesource.com/c/sdk/+/517744/comment/31d2dbb9_03f048e1/:

    This example leads me to wonder about an exception we might make: What if the rule ignores return x where x is exactly a call to Future.syncValue, and maybe Future.value and Future.sync? It might seem a little bit arbitrary, but while cleaning internal code I found a surprising number of return Future.value cases. I think you see it like:

    Future<List<int>> f() {
      try {
        return service.asyncFetchStuff();
      catch (_) {
        return Future.value([]);
      }
    }
    

    (similar for async functions, but the Future.value wrapper is generally unnecessary there)

    It seems like the Futures that could throw asynchronously are: Future.new, Future.delayed, Future.microtask, Future.sync (wait, no...), and any arbitrary Future which is not a Future instance creation.

    So I just want to know if anyone knows of another case we should consider here, @lrhn / @eernstg? Are these the cases where we want to avoid reporting? I'm guessing these are fine because they would throw before creating the future itself?

    • Future.value
    • Future.syncValue
    • Future.sync

    Also, if these are ignored by the analyzer warning unawaited_return_in_try_block, I think we should report them at the linter rule async_return_with_no_await (if the body is async), so we keep all cases awaited for that language suggestion.

  22. natebosch commented on Jul 14, 2026

    @natebosch
    Member

    Only Future.value and Future.syncValue would be safe to ignore, Future.sync can raise an async error.

  23. FMorschel commented on Sep 30, 2026

    @FMorschel
    Contributor

    Okay, I went looking into our (hopefully) last cases at:

    https://github.com/dart-lang/core/blob/08e4022160c465780690c43ffdbce60812975d2c/pkgs/async/lib/src/cancelable_operation.dart#L579

    https://github.com/dart-lang/core/blob/08e4022160c465780690c43ffdbce60812975d2c/pkgs/async/lib/src/stream_group.dart#L238-L239

    The problem here is that these Functions rely on the result being Future<void>? (the null option is important). Should I try to make some changes here, or add ignores or what?

    I'd love your opinions or suggestions, @lrhn and @eernstg (or anyone else you can think of who can maybe come up with a fix for something like this).

  24. natebosch commented on Oct 29, 2026

    @natebosch
    Member

    73. Here is the CL to make this analyzer warning trigger on non-async cases too: https://dart-review.googlesource.com/c/sdk/+/517744

    I'm having a hard time finding the part of the discussion justifying this specific decision. Can anyone remind me what the context was?

    86. https://github.com/dart-lang/core/blob/08e4022160c465780690c43ffdbce60812975d2c/pkgs/async/lib/src/cancelable_operation.dart#L579

            return result.catchError(completer.completeErrorIfPending);

    I don't know how feasible it is to implement, but a future.catchError might be safe and if we can recognize the scenario would probably only leave a small window for false-negatives.

    https://github.com/dart-lang/core/blob/08e4022160c465780690c43ffdbce60812975d2c/pkgs/async/lib/src/stream_group.dart#L238-L239

                if (subscription != null) return subscription.cancel();
                return entry.key.listen(null).cancel();

    These we don't expect to throw, but I'm not sure if we should rely on that. @lrhn - WDYT about using return subscription.cancel()?.ignore(); if we could make the lint recognize calls to Future.ignore?

  25. FMorschel commented on Oct 29, 2026

    @FMorschel
    Contributor

    @natebosch, it was @bwilkerson's #62555 (comment):

    61. [...] And unless there's a reason why it would be a bad idea, I think the lint should continue to produce a diagnostic even when there is no async.

    Basically, the idea is that since you are wrapping the return statement inside a try, you probably meant to catch things there. And without the await there, this is not possible today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P4area-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-proposaltype-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