androidandroid-internet

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();
  }

Solution

  • 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.