withRetry<T> function

Future<T> withRetry<T>(
  1. Future<T> fn(), {
  2. int maxRetries = 2,
  3. Duration delay = const Duration(seconds: 30),
})

Implementation

Future<T> withRetry<T>(
  Future<T> Function() fn, {
  int maxRetries = 2,
  Duration delay = const Duration(seconds: 30),
}) async {
  for (var attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (_) {
      if (attempt == maxRetries) {
        rethrow;
      }

      stdout.writeln(
        'Attempt $attempt/$maxRetries failed, '
        'retrying in ${delay.inSeconds}s...',
      );
      await Future<void>.delayed(delay);
    }
  }

  throw StateError('Unreachable');
}