retryInterceptor static method

Interceptor retryInterceptor({
  1. int maxRetries = 3,
  2. Duration retryDelay = const Duration(seconds: 1),
  3. bool retryOnError(
    1. DioException
    )?,
})

Creates a retry interceptor that retries failed requests

maxRetries - Maximum number of retry attempts retryDelay - Delay between retries retryOnError - Function to determine if an error should trigger a retry

Implementation

static Interceptor retryInterceptor({
  int maxRetries = 3,
  Duration retryDelay = const Duration(seconds: 1),
  bool Function(DioException)? retryOnError,
}) {
  return InterceptorsWrapper(
    onError: (error, handler) async {
      if (error.requestOptions.extra['retryCount'] == null) {
        error.requestOptions.extra['retryCount'] = 0;
      }

      final retryCount = error.requestOptions.extra['retryCount'] as int;

      if (retryCount < maxRetries) {
        final shouldRetry =
            retryOnError?.call(error) ??
            (error.type == DioExceptionType.connectionTimeout ||
                error.type == DioExceptionType.receiveTimeout ||
                error.type == DioExceptionType.sendTimeout ||
                (error.response?.statusCode != null &&
                    error.response!.statusCode! >= 500));

        if (shouldRetry) {
          error.requestOptions.extra['retryCount'] = retryCount + 1;
          print(
            '🔄 [Google Maps API] Retrying request (${retryCount + 1}/$maxRetries)',
          );

          await Future.delayed(retryDelay);
          try {
            final response = await Dio().fetch(error.requestOptions);
            handler.resolve(response);
            return;
          } catch (e) {
            // Continue to next retry or fail
          }
        }
      }

      handler.next(error);
    },
  );
}