diff --git a/retry/lib/retry.dart b/retry/lib/retry.dart index bde22c25..9739aef9 100644 --- a/retry/lib/retry.dart +++ b/retry/lib/retry.dart @@ -118,10 +118,15 @@ class RetryOptions { /// If no [retryIf] function is given this will retry any for any [Exception] /// thrown. To retry on an [Error], the error must be caught and _rethrown_ /// as an [Exception]. + /// + /// If call [fn] retrying does not satisfies [retryIf] or [attempt] is exhausted, + /// the result of invoking the [orElse] function is returned. + /// If [orElse] is omitted, the exception on retry will be thrown. Future retry( FutureOr Function() fn, { FutureOr Function(Exception)? retryIf, FutureOr Function(Exception)? onRetry, + FutureOr Function(Exception)? orElse, }) async { var attempt = 0; // ignore: literal_only_boolean_expressions @@ -132,7 +137,11 @@ class RetryOptions { } on Exception catch (e) { if (attempt >= maxAttempts || (retryIf != null && !(await retryIf(e)))) { - rethrow; + if (orElse != null) { + return orElse(e); + } else { + rethrow; + } } if (onRetry != null) { await onRetry(e); @@ -171,6 +180,10 @@ class RetryOptions { /// If no [retryIf] function is given this will retry any for any [Exception] /// thrown. To retry on an [Error], the error must be caught and _rethrown_ /// as an [Exception]. +/// +/// If call [fn] retrying does not satisfies [retryIf] or [attempt] is exhausted, +/// the result of invoking the [orElse] function is returned. +/// If [orElse] is omitted, the exception on retry will be thrown. Future retry( FutureOr Function() fn, { Duration delayFactor = const Duration(milliseconds: 200), @@ -179,10 +192,11 @@ Future retry( int maxAttempts = 8, FutureOr Function(Exception)? retryIf, FutureOr Function(Exception)? onRetry, + FutureOr Function(Exception)? orElse, }) => RetryOptions( delayFactor: delayFactor, randomizationFactor: randomizationFactor, maxDelay: maxDelay, maxAttempts: maxAttempts, - ).retry(fn, retryIf: retryIf, onRetry: onRetry); + ).retry(fn, retryIf: retryIf, onRetry: onRetry,orElse: orElse); diff --git a/retry/test/retry_test.dart b/retry/test/retry_test.dart index 75930633..e76e23d7 100644 --- a/retry/test/retry_test.dart +++ b/retry/test/retry_test.dart @@ -131,5 +131,12 @@ void main() { await expectLater(f, throwsA(isException)); expect(count, equals(2)); }); + + test('retry when orElse is not omitted', () async { + final result = await retry(() { + throw Exception(); + }, orElse: (_) => 1, maxAttempts: 2); + expect(result, 1); + }); }); }