-
Notifications
You must be signed in to change notification settings - Fork 1.7k
catchError and onError do not catch error with function without "async" keyword #50361
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This is expected behavior. The The We generally recommend that asynchronous functions (those returning a What you can do is to either change Future<int> calcOrThrow(int value) async {
if (value < 0) {
throw Exception('ERROR');
}
return await calc(value);
} or to make it throw "asynchronously" by returning an error future: Future<int> calcOrThrow(int value) { // No "async" keyword here
if (value < 0) {
return Future.error(Exception('ERROR'));
}
return calc(value);
} |
@lrhn Even if this is expected behaviour, I think it is error-prone. Now that I know |
Asynchronous functions (and So we can't just disallow unsafe code. The lint to disallow asynchronous operations in non-async functions is called We could consider a lint to prevent (obvious) synchronous throwing in non- |
@lrhn int calcOrThrow(int value) {
if (value < 0) {
throw Exception('ERROR');
}
calc(value); // lint
// return calc(value); // error (A value of type 'Future<int>' can't be returned from ...)
}
Hope it will be added. Thank you! |
It occurred only with some functions, so I compared with other functions and found that it depended on whether a function had the "async" keyword. If I add
async
to calcOrThrow() above,onError()
can catch the exception thrown there.However, it is possible to omit
async
because calcOrThrow() directly returns the future returned from calc(). The analyzer warns nothing about it, so I think this misuse (or a bug?) can easily happen.It is also confusing that try-catch worked fine regardless of
async
.It seems this issue exists in
whenComplete()
and theonError
argument ofthen()
too.The text was updated successfully, but these errors were encountered: