Error Handling with Futures
Asynchronous operations fail in all kinds of ways: networks drop, servers time out, data is malformed. A future that fails completes with an error, and that error travels to whoever awaits it. With async/await you handle it using the same try/catch/finally as synchronous code.
try/catch around await
class NetworkException implements Exception {
final int statusCode;
NetworkException(this.statusCode);
@override
String toString() => 'NetworkException($statusCode)';
}
Future<String> fetchProfile(int id) async {
await Future.delayed(Duration(milliseconds: 10));
if (id < 0) throw ArgumentError.value(id, 'id');
if (id == 404) throw NetworkException(404);
return 'profile#$id';
}
Future<void> show(int id) async {
try {
final p = await fetchProfile(id);
print('ok: $p');
} on NetworkException catch (e) {
print('network problem: ${e.statusCode}');
} on ArgumentError catch (e) {
print('bad argument: ${e.invalidValue}');
} finally {
print(' (request $id finished)');
}
}
Future<void> main() async {
await show(7);
await show(404);
await show(-1);
}ok: profile#7
(request 7 finished)
network problem: 404
(request 404 finished)
bad argument: -1
(request -1 finished)
Even though the error is thrown inside fetchProfile after a delay, it surfaces at the await in show — exactly where you'd expect.
The un-awaited future trap
If you call an async function without awaiting it, a try around the call can't catch its error — the try block has already finished by the time the error happens:
Future<void> failLater() async {
await Future.delayed(Duration(milliseconds: 5));
throw StateError('boom');
}
Future<void> main() async {
try {
failLater(); // missing await!
print('call returned, try block ends');
} catch (e) {
print('never reached');
}
}call returned, try block ends
Unhandled exception:
Bad state: boom
#0 failLater (file:///app/bin/main.dart:3:3)
...The error has nowhere to go, so it becomes an unhandled exception and the program crashes. The fix is to await the future — or, if you really want fire-and-forget, to attach a handler explicitly:
Future<void> failLater(String label) async {
await Future.delayed(Duration(milliseconds: 5));
throw StateError('boom in $label');
}
Future<void> main() async {
try {
await failLater('awaited call'); // the error surfaces here
} catch (e) {
print('caught: $e');
}
// fire-and-forget, but with an explicit handler
final background = failLater('background job')
.catchError((Object e) => print('handled: $e'));
print('main keeps going');
await background; // only so this demo prints before exiting
}caught: Bad state: boom in awaited call
main keeps going
handled: Bad state: boom in background job
The unawaited_futures and discarded_futures lints catch the missing-await mistake for you.
Timeouts
future.timeout(duration) completes with a TimeoutException if the original future takes too long. You can also supply a fallback value with onTimeout:
import 'dart:async';
Future<String> slowServer() =>
Future.delayed(Duration(milliseconds: 200), () => 'fresh data');
Future<void> main() async {
try {
final data = await slowServer().timeout(Duration(milliseconds: 20));
print(data);
} on TimeoutException catch (e) {
print('timed out after ${e.duration?.inMilliseconds} ms');
}
final cached = await slowServer().timeout(
Duration(milliseconds: 20),
onTimeout: () => 'cached data',
);
print(cached);
}timed out after 20 ms
cached data
Retrying with backoff
A retry loop is plain for + try/catch + await:
var _calls = 0;
Future<String> flakyRequest() async {
_calls++;
await Future.delayed(Duration(milliseconds: 2));
if (_calls < 3) throw Exception('temporary failure #$_calls');
return 'success on call $_calls';
}
Future<T> retry<T>(Future<T> Function() task, {int attempts = 4}) async {
var delay = Duration(milliseconds: 5);
for (var i = 1; ; i++) {
try {
return await task();
} catch (e) {
if (i == attempts) rethrow;
print('attempt $i failed: $e — retrying in ${delay.inMilliseconds} ms');
await Future.delayed(delay);
delay *= 2;
}
}
}
Future<void> main() async {
print(await retry(flakyRequest));
}attempt 1 failed: Exception: temporary failure #1 — retrying in 5 ms
attempt 2 failed: Exception: temporary failure #2 — retrying in 10 ms
success on call 3
Note return await task(); — the await is essential inside try. Without it, the function would return the future and its error would escape the catch.
Errors in Future.wait
By default Future.wait fails with the first error. Dart 3's .wait on a list or record throws a ParallelWaitError that carries all the values and errors, so you can see which ones failed:
import 'dart:async';
Future<int> ok(int v) async => v;
Future<int> bad(String msg) async => throw FormatException(msg);
Future<void> main() async {
try {
await Future.wait([ok(1), bad('first'), bad('second')]);
} on FormatException catch (e) {
print('Future.wait: ${e.message}');
}
try {
await [ok(1), bad('x'), ok(3)].wait;
} on ParallelWaitError<List<int?>, List<AsyncError?>> catch (e) {
print('values: ${e.values}');
print('failed indexes: ${[for (var i = 0; i < e.errors.length; i++) if (e.errors[i] != null) i]}');
}
}Future.wait: first
values: [1, null, 3]
failed indexes: [1]
Summary
| Technique | Use |
|---|---|
try { await f(); } on T catch (e) { } |
Handle a specific async failure |
finally |
Cleanup after success or failure |
.timeout(d, onTimeout: …) |
Bound how long you wait |
.catchError(...) |
Handling in then-style code |
return await inside try |
Make sure the error is caught here |
.wait + ParallelWaitError |
Inspect every result of parallel work |
Test yourself
Why doesn't try { failLater(); } catch (e) {} catch the async error?
- catch doesn't work with exceptions
- The future isn't awaited, so the try block ends before the error happens
- Async errors can't be caught
- failLater must be marked sync
What exception does future.timeout(d) throw when time runs out (without onTimeout)?
- StateError
- TimeoutException
- AsyncError
- CancelledException
Inside a try block in an async function, why write return await task(); instead of return task();?
- It's faster
- So errors from the future are caught by this try/catch
- It's required syntax
- To avoid a memory leak