withRetry<T> function

Future<T> withRetry<T>({
  1. required Future<T> operation(
    1. int attempt
    ),
  2. RetryConfig config = RetryConfig.defaultConfig,
  3. void onRetry(
    1. int attempt,
    2. Duration delay,
    3. ApiError error
    )?,
})

Execute an operation with retry logic.

Returns the result of a successful attempt or throws with the last error. onRetry is called before each retry with the current attempt number and delay.

Implementation

Future<T> withRetry<T>({
  required Future<T> Function(int attempt) operation,
  RetryConfig config = RetryConfig.defaultConfig,
  void Function(int attempt, Duration delay, ApiError error)? onRetry,
}) async {
  final context = RetryContext();

  while (true) {
    context.attempt++;
    try {
      return await operation(context.attempt);
    } catch (e) {
      final error = e is ApiError ? e : classifyException(e);
      final decision = shouldRetry(
        error: error,
        context: context,
        config: config,
      );

      if (!decision.shouldRetry) {
        throw ApiError(
          type: error.type,
          message: decision.abortReason ?? error.message,
          statusCode: error.statusCode,
        );
      }

      onRetry?.call(context.attempt, decision.delay!, error);
      await Future.delayed(decision.delay!);
    }
  }
}