withRetry<T> method

Future<T> withRetry<T>({
  1. required Future<T> action(),
  2. required String actionName,
  3. int maxRetries = 5,
  4. Duration retryDelay(
    1. int retryCount
    ) = _defaultRetryDelay,
})

Executes an action with retry logic.

This method attempts to execute the provided action and retries if it fails with an ArchethicTooManyRequestsException. The delay between retries is calculated using the retryDelay function.

  • action: The asynchronous function to execute.
  • maxRetries: The maximum number of retries. Defaults to 5.
  • retryDelay: A function that calculates the delay between retries. Defaults to _defaultRetryDelay.

Returns the result of the action if successful.

Throws:

Implementation

Future<T> withRetry<T>({
  required Future<T> Function() action,
  required String actionName,
  int maxRetries = 5,
  Duration Function(int retryCount) retryDelay = _defaultRetryDelay,
}) async {
  var retryCount = 0;

  while (retryCount < maxRetries) {
    try {
      return await action();
    } catch (e) {
      if (e is ArchethicTooManyRequestsException ||
          e is ArchethicServiceUnavailableException) {
        retryCount++;
        if (retryCount >= maxRetries) {
          _logger.severe('Max retries reached for action: $actionName');
          rethrow;
        }

        final delay = retryDelay(retryCount);

        _logger.warning(
          'Retrying action "$actionName" in $delay (attempt $retryCount/$maxRetries)',
        );
        await Future.delayed(delay);
      } else {
        rethrow;
      }
    }
  }

  throw Exception('Max retries exceeded for action: $actionName');
}