onError method

  1. @override
Future onError (DioError dioError)

The callback will be executed on error.

If you want to resolve the request with some custom data, you can return a Response object or return dio.resolve. If you want to continue the request, return the DioError object.

Implementation

@override
Future onError(DioError dioError) async {
  int _responseCode = dioError.response.statusCode;
  final _existingAuthToken = await _authApi.getAuthTokenFromCache();

  if (_existingAuthToken?.token != null && _responseCode == 401) {
    _dio.interceptors.requestLock.lock();
    _dio.interceptors.responseLock.lock();
    print('Requesting for new token');

    try {
      final _authToken =
          await _authApi.refreshAccessToken(_existingAuthToken);

      await _authApi.cacheAuthToken(_authToken);

      RequestOptions options = dioError.response.request;
      _dio.interceptors.requestLock.unlock();
      _dio.interceptors.responseLock.unlock();
      return _dio.request(options.path, options: options);
    } catch (e) {
      print('Interceptor error ===> $e');
      super.onError(e);
    }
  } else {
    super.onError(dioError);
  }
}