retryTimes<T> function
Retries fn up to times attempts;
rethrows on final failure.
Audited: 2026-06-12 11:26 EDT
Implementation
Future<T> retryTimes<T>(
AsyncAction<T> fn,
int times,
) async {
// At least one attempt: a non-positive `times` would otherwise rethrow on the
// first failure (0 retries) yet still run fn once — clamp so the count is sane.
final int maxAttempts = times < 1 ? 1 : times;
int attempts = 0;
while (true) {
try {
return await fn();
} on Object catch (e, st) {
attempts++;
if (attempts >= maxAttempts) {
// Structured log instead of debugPrint, so the stack trace is not printed
// to stdout. The error is rethrown to the caller below.
log('retryTimes failed after $times', error: e, stackTrace: st);
rethrow;
}
}
}
}