dart-neats icon indicating copy to clipboard operation
dart-neats copied to clipboard

feat: orElse callback when retries is exhausted

Open drown0315 opened this issue 2 years ago • 1 comments

reference by https://github.com/google/dart-neats/pull/167

drown0315 avatar Jul 25 '23 10:07 drown0315

I could use this as:

final msg = await retry(
  getMessage,
  retryIf: (e) => e is TimeoutException,
  orElse: (e) => 'failed to get data',
);

But I could also do:

final msg = await retry(
  getMessage,
  retryIf: (e) => e is TimeoutException,
).catchError((e) => 'failed to get data');

Maybe, instead of creating a new orElse parameter, we should improve:

  • examples,
  • tests, and,
  • API documentation, to clearly help users discover that you can elegantly combine this with .catchError(). If you want to produce a value, when retry fails.

I think a section in the README.md would be fantastic.

Maybe, even a hint in the documentation for the retry() function would be fine. Perhaps something like:

/// Call [fn] retrying so long as [retryIf] return `true` for the exception
/// thrown, up-to [maxAttempts] times.
///
/// Defaults to 8 attempts, sleeping as following after 1st, 2nd, 3rd, ...,
/// 7th attempt:
///  1. 400 ms +/- 25%
///  2. 800 ms +/- 25%
///  3. 1600 ms +/- 25%
///  4. 3200 ms +/- 25%
///  5. 6400 ms +/- 25%
///  6. 12800 ms +/- 25%
///  7. 25600 ms +/- 25%
///
/// ```dart
/// final response = await retry(
///   // Make a GET request
///   () => http.get('https://google.com').timeout(Duration(seconds: 5)),
///   // Retry on SocketException or TimeoutException
///   retryIf: (e) => e is SocketException || e is TimeoutException,
/// );
/// print(response.body);
/// ```
///
/// 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].
///
/// To always produce a value, even when retries are failed or an exception not
/// matched by [retryIf] is encountered, combine [retry] with [Future.catchError].
/// ```dart
/// final body = await retry(
///   () => http.read('https://google.com').timeout(Duration(seconds: 5)),
///   retryIf: (e) => e is SocketException || e is TimeoutException,
/// ).catchError((e) => 'failed to get data');
/// print(body);
/// ```

jonasfj avatar Jul 27 '23 09:07 jonasfj