Skip to content

Commit

Permalink
feat: add onRetryFailure to retry
Browse files Browse the repository at this point in the history
  • Loading branch information
drown0315 committed Jul 26, 2023
1 parent 545dc09 commit 0c0e20c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
12 changes: 10 additions & 2 deletions retry/lib/retry.dart
Original file line number Diff line number Diff line change
Expand Up @@ -121,22 +121,27 @@ final class RetryOptions {
Future<T> retry<T>(
FutureOr<T> Function() fn, {
FutureOr<bool> Function(Exception)? retryIf,
@Deprecated('Use `onRetryFailure` instead of `onRetry`')
FutureOr<void> Function(Exception)? onRetry,
FutureOr<void> Function(Exception, StackTrace)? onRetryFailure,
}) async {
var attempt = 0;
// ignore: literal_only_boolean_expressions
while (true) {
attempt++; // first invocation is the first attempt
try {
return await fn();
} on Exception catch (e) {
} on Exception catch (e, st) {
if (attempt >= maxAttempts ||
(retryIf != null && !(await retryIf(e)))) {
rethrow;
}
if (onRetry != null) {
await onRetry(e);
}
if (onRetryFailure != null) {
await onRetryFailure(e, st);
}
}

// Sleep for a delay
Expand Down Expand Up @@ -178,11 +183,14 @@ Future<T> retry<T>(
Duration maxDelay = const Duration(seconds: 30),
int maxAttempts = 8,
FutureOr<bool> Function(Exception)? retryIf,
@Deprecated('Use `onRetryFailure` instead of `onRetry`')
FutureOr<void> Function(Exception)? onRetry,
FutureOr<void> Function(Exception, StackTrace)? onRetryFailure,
}) =>
RetryOptions(
delayFactor: delayFactor,
randomizationFactor: randomizationFactor,
maxDelay: maxDelay,
maxAttempts: maxAttempts,
).retry(fn, retryIf: retryIf, onRetry: onRetry);
).retry(fn,
retryIf: retryIf, onRetry: onRetry, onRetryFailure: onRetryFailure);
13 changes: 13 additions & 0 deletions retry/test/retry_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -131,5 +131,18 @@ void main() {
await expectLater(f, throwsA(isException));
expect(count, equals(2));
});

test('call onRetryFailure when exception on retry', () async {
var count = 0;
await retry(() {
count++;
if (count == 1) {
throw FormatException('Retry will be okay');
}
}, onRetryFailure: (e, st) {
expect(e, isA<FormatException>());
expect(st, isA<StackTrace>());
});
});
});
}

0 comments on commit 0c0e20c

Please sign in to comment.