onError method

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

Called when an exception was occurred during the request.

Implementation

@override
Future onError(DioException err, ErrorInterceptorHandler handler) async {
  if (err.requestOptions.disableRetry) return super.onError(err, handler);
  var attempt = err.requestOptions._attempt + 1;
  final shouldRetry =
      attempt <= retries && await defaultRetryEvaluator(err, attempt);

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

  err.requestOptions._attempt = attempt;
  final delay = _getDelay(attempt);
  logPrint?.call(
    '[${err.requestOptions.uri}] 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);
  var header = <String, dynamic>{}..addAll(err.requestOptions.headers);
  err.requestOptions.headers = header;
  try {
    await dio.fetch<void>(err.requestOptions).then(
          (value) => handler.resolve(value),
        );
  } on DioException catch (e) {
    super.onError(e, handler);
  } catch (e) {
    logPrint!('error: $e');
  }
}