avoid-uncaught-future-errors
preset: recommended
Warns when an error from a Future
inside a try / catch block might not be caught.
If a Future
that results in an error is awaited only after an async gap (ex. another Future
is being awaited), the error will be caught by the global error handler as well as the outer try / catch block. This behavior is by design and may lead to unexpected errors being shown.
Example
❌ Bad:
Future<void> asyncFunctionAssignFuture() async {
try {
final future = asyncFunctionError();
await Future.delayed(const Duration(seconds: 1));
await future; // LINT: If this 'Future' results in an error, the error will be uncaught due to an async gap.
} catch (e) {
print('caught in function: $e');
}
}
✅ Good:
Future<void> asyncFunctionAssignFuture() async {
try {
final future = asyncFunctionError().catchError((error) { ... }); // Correct, catches any potential error
await Future.delayed(const Duration(seconds: 1));
await future;
} catch (e) {
print('caught in function: $e');
}
}
Additional Resources
- https://github.com/dart-lang/sdk/issues/52729
- https://api.dart.dev/stable/3.0.5/dart-async/Future-class.html#:~:text=however%2C%20it%20also%20means%20that%20error%20handlers%20should%20be%20installed%20early