retryWithPolicy<T> function
Retries fn up to maxAttempts with delay between attempts. Optional onRetry.
Implementation
Future<T> retryWithPolicy<T>(
Future<T> Function() fn, {
int maxAttempts = 3,
Duration delay = retryPolicyDefaultDelay,
void Function(Object error, int attempt)? onRetry,
}) async {
int attempt = 0;
while (true) {
try {
return await fn();
} on Object catch (e, st) {
log('retryWithPolicy attempt $attempt', error: e);
attempt++;
// ignore: saropa_lints/avoid_ignoring_return_values -- throwWithStackTrace returns Never; there is no value to capture
if (attempt >= maxAttempts) Error.throwWithStackTrace(e, st);
onRetry?.call(e, attempt);
await Future<void>.delayed(delay);
}
}
}