onError method

  1. @override
void onError(
  1. DioException err,
  2. ErrorInterceptorHandler handler
)
override

Called when an exception was occurred during the request.

Implementation

@override
void onError(
    DioException err,
    ErrorInterceptorHandler handler,
    ) async {
  // Check if should retry
  if (!_shouldRetry(err)) {
    return handler.next(err);
  }

  // Get current retry count
  final retryCount = err.requestOptions.extra['retryCount'] as int? ?? 0;

  // Check if max attempts reached
  if (retryCount >= config.maxAttempts) {
    return handler.next(err);
  }

  // Calculate delay with exponential backoff
  final delay = _calculateDelay(retryCount);

  // Log retry attempt (if you have a logger)
  _logRetry(err, retryCount, delay);

  // Wait before retry
  await Future.delayed(delay);

  // Increment retry count
  err.requestOptions.extra['retryCount'] = retryCount + 1;

  // Retry the request using DioProvider (maintains all interceptors!)
  try {
    final response = await dioProvider.dio.fetch(err.requestOptions); // ✅ Fixed!
    return handler.resolve(response);
  } on DioException catch (e) {
    // If retry fails, it will go through onError again
    // and either retry again or give up based on the new error
    return handler.next(e);
  } catch (e) {
    return handler.next(err);
  }
}