Dart Future Wait Errors
Future.wait completes with an error when one of its futures fails. The error shapes of wait decide which error the waiting code receives.
One failing future fails the wait
The good future gives 5 and the bad future throws a FormatException. Wait completes with that error, and the typed catch prints its message.
import 'dart:async';
Future<int> good() async => 5;
Future<int> bad() async => throw FormatException('bad number');
Future<void> main() async {
try {
var results = await Future.wait([good(), bad()]);
print(results);
} on FormatException catch (e) {
print('FormatException: ${e.message}');
}
}The same error with eagerError
The eagerError option is set to true on the same pair of futures. The catch receives the same FormatException with the same message.
import 'dart:async';
Future<int> good() async => 5;
Future<int> bad() async => throw FormatException('bad number');
Future<void> main() async {
var waiting = Future.wait([good(), bad()], eagerError: true);
try {
await waiting;
} on FormatException catch (e) {
print('eager caught: ${e.message}');
}
}Two failing futures, one report
The first future throws a FormatException and the second throws an ArgumentError. Wait reports the FormatException, the first error to complete, and the other error is consumed.
import 'dart:async';
Future<int> badFirst() async => throw FormatException('bad number');
Future<int> badSecond() async => throw ArgumentError('bad argument');
Future<void> main() async {
try {
await Future.wait([badFirst(), badSecond()]);
} on FormatException catch (e) {
print('first error: ${e.message}');
}
}Example
import 'dart:async';
Future<int> score(int n) async => n;
Future<int> broken() async => throw FormatException('bad number');
Future<void> main() async {
try {
var results = await Future.wait([score(10), broken(), score(30)]);
print(results);
} on FormatException catch (e) {
print('summary: one future failed with ${e.message}');
}
}Key points
- When one future in the list fails, wait completes with that error instead of a list of results.
- Code awaiting wait can catch that error with a typed catch, and the message of the error stays intact.
- Setting eagerError to true still delivers the same FormatException to the catch in this shape.
- When two futures fail, wait reports the first error to complete.
- Wait consumes the errors of its futures, so a second failing future adds no second report.
- A successful result list is not delivered when wait completes with an error.
In this example, three futures run under one wait and the middle one throws a FormatException. Wait delivers no result list, and the catch prints one summary line built from the message of the caught error.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
Two futures in a Future.wait list both fail. Which error does the awaiting code receive?