onError method

  1. @override
Future onError(
  1. DioError err,
  2. ErrorInterceptorHandler handler
)

The callback will be executed on error.

If you want to continue the error , call handler.next.

If you want to complete the response with some custom data directly, you can resolve a Response object with handler.resolve and other error interceptor(s) will be skipped.

If you want to complete the response with an error message directly, you can reject a DioError object with handler.reject, and other error interceptor(s) will be skipped.

Implementation

@override
Future onError(DioError err, ErrorInterceptorHandler handler) async {
  if (err.requestOptions.disableRetry) {
    return super.onError(err, handler);
  }

  final attempt = err.requestOptions._attempt + 1;
  final shouldRetry = attempt <= retries && await _shouldRetry(err, attempt);

  if (!shouldRetry) {
    return super.onError(err, handler);
  }

  err.requestOptions._attempt = attempt;
  final delay = _getDelay(attempt);
  logPrint?.call(
    '[${err.requestOptions.path}] An error occurred during request, '
    'trying again '
    '(attempt: $attempt/$retries, '
    'wait ${delay.inMilliseconds} ms, '
    'error: ${err.error})',
  );

  if (delay != Duration.zero) {
    await Future<void>.delayed(delay);
  }

  try {
    await dio
        .fetch<void>(err.requestOptions)
        .then((value) => handler.resolve(value));
  } on DioError catch (e) {
    super.onError(e, handler);
  }
}