You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Linter rule to prevent returning futures from the try block #62555
There have been multiple times when I’ve accidentally written code like this:
Future<Foo> doSomethingUsefulAndGetFoo() async {
try {
/* do something useful */returngetFooButMayFail(); // wrong!
} onGettingFooFailedException {
/* do something with the exception */rethrow;
}
}
While the right code would look like so:
Future<Foo> doSomethingUsefulAndGetFoo() async {
try {
/* do something useful */returnawaitgetFooButMayFail();
} onGettingFooFailedException {
/* 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.
Reacted by Stéphane Archer, Hector Aguero, Piotr Rogulski, Simon Binder, Birju Vachhani, André Sousa and Pascal Welsch
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
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.
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.
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.
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.)
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.
[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.
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.
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 analyzerwarning (unawaited_return_in_try_block).
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:
(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.
Reacted by Sam Rawlins, Mohellebi Abdessalem and Birju Vachhani
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).
I don't know how feasible it is to implement, but a future.catchErrormight be safe and if we can recognize the scenario would probably only leave a small window for false-negatives.
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?
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.
Activity
[-]Linter rule to prevent returning futures from the try/catch block[/-][+]Linter rule to prevent returning futures from the try block[/+]FMorschel commentedon Jan 31, 2026
I love this idea!
And I would actually prefer if we had the exact opposite of
unnecessary_await_in_return(if the body isasyncwe suggest people to add theawait). 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
FMorschel commentedon Feb 2, 2026
I found the issue I was referring to:
asyncfunctions. language#870eernstg commentedon Feb 2, 2026
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
asyncfunctions 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 markedasyncsuch that the static type ofeis a subtype ofFuture<T>whereTis the future value type of the nearest enclosing function.This approach has false negatives; in particular, the static type of
ecould bedynamic, 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 ofeyields a future which is completed with an error.FMorschel commentedon Feb 2, 2026
Oh, so this is basically a duplicate of (with a different name but basically the same idea):
Found it at #44395.
eernstg commentedon Feb 2, 2026
Right, I forgot about that one!
FMorschel commentedon Feb 2, 2026
And as mentioned in this comment from @natebosch:
I strongly agree with this.
bwilkerson commentedon Feb 2, 2026
I have no objection to adding a warning with no false positives.
And I have no objection to removing the lint.
FMorschel commentedon Feb 2, 2026
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.eernstg commentedon Feb 3, 2026
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.
srawlins commentedon Feb 4, 2026
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.)
srawlins commentedon Feb 4, 2026
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 ofeisFutureOr<whatever>return e;where the static type ofeis a type variable,T, with boundFuture<something>, or boundFutureOr<something>return e;where the static type ofeis a subtype (or assignable to?)Future<something>; this would be like various Future subtypes that are around likeSyncFutureI think, andCancellableFuture.FMorschel commentedon Feb 4, 2026
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.
Yes.
I think it should, but I'll be sure to add a test case.
This one, I'm pretty certain it should, but again, I'll add another test case.
Thanks!
FMorschel commentedon Feb 4, 2026
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
tryblocks (to avoid the bug in question here), and the lint would trigger allreturn(maybeyield) occurrences (aiming to push dart-lang/language#870).I can make separate CLs; I just want to know what our goal is.
51 remaining items
FMorschel commentedon Jun 8, 2026
Thanks, @eernstg!
That is what I thought.
But now, if we consider the non-
trycases. Should we add the fix to those? Since removing theasyncwouldn't make any difference to those.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 theanalyzerwarning (unawaited_return_in_try_block).[camera][google_fonts] Fixes future warning for `await`ing `Future` r…
FMorschel commentedon Jun 26, 2026
Here is the CL to make this
analyzerwarning trigger on non-asynccases too: https://dart-review.googlesource.com/c/sdk/+/517744FMorschel commentedon Jul 2, 2026
I've opened this:
instantiateImageCodecFromBufferflutter/flutter#188910To fix the above CL bots.
FMorschel commentedon Jul 2, 2026
I've also opened:
async_return_with_no_awaithave aRemove asyncfix #63737So we can discuss that fix over there. This way, once the CL above lands, this issue will be closed.
FMorschel commentedon Jul 14, 2026
@srawlins wrote at https://dart-review.googlesource.com/c/sdk/+/517744/comment/31d2dbb9_03f048e1/:
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.valueFuture.syncValueFuture.syncAlso, if these are ignored by the
analyzerwarningunawaited_return_in_try_block, I think we should report them at thelinterruleasync_return_with_no_await(if the body isasync), so we keep all casesawaited for that language suggestion.natebosch commentedon Jul 14, 2026
Only
Future.valueandFuture.syncValuewould be safe to ignore,Future.synccan raise an async error.Adds missing await on `instantiateImageCodecFromBuffer` (flutter#188910)
[DAS] Adds `Remove async` fix for `async_return_with_no_await`
Refactors `try` to avoid `unawaited_return_in_try_block` case (flutte…
Fixes future warning for `await`ing `Future` returns in `async` bodie…
Updates tests commit (#183301)
FMorschel commentedon Sep 30, 2026
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>?(thenulloption 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).
natebosch commentedon Oct 29, 2026
I'm having a hard time finding the part of the discussion justifying this specific decision. Can anyone remind me what the context was?
I don't know how feasible it is to implement, but a
future.catchErrormight be safe and if we can recognize the scenario would probably only leave a small window for false-negatives.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 toFuture.ignore?FMorschel commentedon Oct 29, 2026
@natebosch, it was @bwilkerson's #62555 (comment):
Basically, the idea is that since you are wrapping the return statement inside a
try, you probably meant tocatchthings there. And without theawaitthere, this is not possible today.