Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect 'no internet' connectivity error in Retrofit 2

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.

like image 683
awonderer Avatar asked Aug 03 '16 00:08

awonderer


People also ask

How should I handle no internet connection with retrofit android?

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.

What is the use of interceptor in retrofit android?

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.


1 Answers

Found the solution.

My OfflineException class has to inherit IOException

like image 183
awonderer Avatar answered Sep 30 '22 15:09

awonderer