How to handle java.net.UnknownHostException when using a modification

I use the modification to receive and send data from the server. However, if my phone loses its Internet connection in the middle of the application, I see an error, for example:

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 an exception and show a toast message like "No Internet connection."

I try to make the code this way, but I get the error message: 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(); } 
+6
source share
1 answer

I think you need to have a modified exception in catch.

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

RetroFitError is a common runtime exception. Once it gets into the blocking block, you can really check which error was actually selected by modification. Retrofit has an isNetworkError() method, which you are probably looking for. So you can basically do something like this:

  methodToDeterminErrorType(RetroFitError error){ if(error.isNetworkType()){ //throw a toast } } 

Hope this helps.

+5
source

All Articles