onError method

  1. @override
Future<void> 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<void> onError(DioError err, ErrorInterceptorHandler handler) async {
  final shouldRetry =
      options.retries > 0 && await options.retryEvaluator(err);
  if (shouldRetry) {
    if (options.retryInterval.inMilliseconds > 0) {
      await Future.delayed(options.retryInterval);
    }

    // Update options to decrease retry count before new try
    options = options.copyWith(retries: options.retries - 1);
    err.requestOptions.extra = err.requestOptions.extra
      ..addAll(options.toExtra());

    try {
      logger.warning(
          '[${err.requestOptions.uri}] An error occured during request, trying a again (remaining tries: ${options.retries}, error: ${err.error})');
      // We retry with the updated options

      final _options = Options(
          contentType: err.requestOptions.contentType,
          method: err.requestOptions.method,
          headers: err.requestOptions.headers,
          extra: err.requestOptions.extra,
          validateStatus: err.requestOptions.validateStatus);

      await dio.request(
        err.requestOptions.path,
        cancelToken: err.requestOptions.cancelToken,
        data: err.requestOptions.data,
        onReceiveProgress: err.requestOptions.onReceiveProgress,
        onSendProgress: err.requestOptions.onSendProgress,
        queryParameters: err.requestOptions.queryParameters,
        options: _options,
      );
    } on Exception {
      rethrow;
    }
  }

  return super.onError(err, handler);
}