Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle java.net.UnknownHostException while using retrofit

I'm using retrofit to get and post data from the server. However, if my phone loses internet connection in middle of the app then I see error like this:

05-10 08:12:05.559  29369-29400/? D/Retrofit﹕ java.net.UnknownHostException: Unable to resolve host "my.server.com": No address associated with hostname
            at java.net.InetAddress.lookupHostByName(InetAddress.java:394)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
            at java.net.InetAddress.getAllByName(InetAddress.java:214)

I would like to handle this error gracefully. I would like to catch the exception and show a toast message like "No internet connection".

I'm trying code like this but I get an error that: java.net.UnknownHostException is never thrown in the try block

  try {
      isTokenValid = MyManager.INSTANCE.getService().validate();
  }
  catch (RetrofitError cause) {
      Response r = cause.getResponse();

      if (r != null && r.getStatus() == 403) {
           isTokenValid = false;
      }
  }
  catch (UnknownHostException exception) {
      Toast.makeText(getBaseContext(), "No internet connection", Toast.LENGTH_SHORT).show();
  }
like image 370
Anthony Avatar asked May 10 '14 12:05

Anthony


People also ask

How do you handle an unknown host exception in Java?

To resolve application level issues, try the following methods: Restart your application. Confirm that your Java application doesn't have a bad DNS cache. If possible, configure your application to adhere to the DNS TTL.

What is retrofit stackoverflow?

Retrofit is a type-safe REST client for Android, Java and Kotlin developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp. See this guide to understand how OkHttp works.


1 Answers

I think you need to have a retrofit exception in the catch.

catch (RetrofitError error) {
    methodToDeterminErrorType(error);
}

The RetroFitError is a generic runtime exception. Once it hits the catch block you can actually verify what kind of a error was actually thrown by retrofit. Retrofit has a method isNetworkError() which is what you are probably looking for. So you can basically do something like this:

methodToDetermineErrorType(RetroFitError error) {
if (error.isNetworkType()) {
    // show a toast
   }
}

Hope this helps.

like image 107
user2511882 Avatar answered Sep 25 '22 04:09

user2511882