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();
}
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With