3

I am getting this error in my logs:

Caused by java.lang.ClassCastException: java.net.UnknownHostException cannot be cast to retrofit2.adapter.rxjava.HttpException

and thats my onError method. The error is probably caused when the device has no connection.

  @Override
        public void onError(Throwable e) {
            assert e != null;
            Timber.d(e);
            HttpException exception = (HttpException) e;
            assert view != null;
            view.hideRefreshSpinner();
            if (exception.code() == HttpURLConnection.HTTP_BAD_REQUEST) {
                view.showSnackbarInvalidError();
            } else {
                view.showUnauthorizedError();
            }

        }
2
  • put your host address Commented Dec 24, 2016 at 9:39
  • The host address is valid, it just I think when the call is made there is a network but no real connection. Commented Dec 25, 2016 at 9:41

1 Answer 1

9

This is happening because you're receiving an instance of java.net.UnknownHostException and not retrofit2.adapter.rxjava.HttpException. If you look at the doc, it says:

  • Direct body (e.g., Observable) calls onNext with the deserialized body for 2XX responses and calls onError with HttpException for non-2XX responses and IOException for network errors.
  • Response wrapped body (e.g., Observable>) calls onNext with a Response object for all HTTP responses and calls onError with IOException for network errors
  • Result wrapped body (e.g., Observable>) calls onNext with a Result object for all HTTP responses and errors.

So you are receiving a network error.

Also see this

You can wrap your code like this:

@Override
public void onError(Throwable e) {
    assert e != null;
    Timber.d(e);
    if (e instanceof HttpException) {
        assert view != null;
        view.hideRefreshSpinner();
        if (((HttpException) e).code() == HttpURLConnection.HTTP_BAD_REQUEST) {
            view.showSnackbarInvalidError();
        } else {
            view.showUnauthorizedError();
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply, I will try it and come back with results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.