withRetry<T> method
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 to5.retryDelay: A function that calculates the delay between retries. Defaults to_defaultRetryDelay.
Returns the result of the action if successful.
Throws:
- The original exception if it is not an ArchethicTooManyRequestsException.
- An Exception with the message "Max retries exceeded" if the maximum number of retries is reached.
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');
}