How can I detect no internet connection error with Retrofit 2?
What I used to do in Retrofit 1 is to implement Client interface and perform connectivity check at execute(Request request).
What I attempted in Retrofit 2 is:
public class RequestInterceptor implements Interceptor {
final ConnectivityManager connectivityManager;
@Inject
public RequestInterceptor(ConnectivityManager connectivityManager) {
this.connectivityManager = connectivityManager;
}
@Override
public Response intercept(Chain chain) throws IOException {
if (isConnected()) {
throw new OfflineException("no internet");
}
Request.Builder r = chain.request().newBuilder();
return chain.proceed(r.build());
}
protected boolean isConnected() {
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
}
I am able to catch it with synchronous Retrofit execution by adding a try-catch block, but not with asynchronous where error is returned as parameter of OnFailure(Call call, Throwable t). App just crashes with OfflineException I throw in the interceptor.
Essentially, you'll create a class that implements Interceptor so that you can perform a network connectivity check before executing the request. If the app knows there is no connectivity, stop and throw exception there. We will need a reference to Context object in order to check connectivity.
Interceptors, according to the documentation, are a powerful mechanism that can monitor, rewrite, and retry the API call. So, when we make an API call, we can either monitor it or perform some tasks. In a nutshell, Interceptors function similarly to airport security personnel during the security check process.
Found the solution.
My OfflineException
class has to inherit IOException
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