Skip to content Skip to sidebar Skip to footer

How To Catch The Exception In Retrofit Android

I have defined the classes as below. I have used dagger with Retrofit here What I am trying to do:: I am trying to catch the OfflineException in the request below how to catch it

Solution 1:

As I know, there is no internet connection the RetrofitError contains a ConnectionException as the cause.

publicclassRetrofitErrorHandlerimplementsErrorHandler {

    @OverridepublicThrowablehandleError(RetrofitError cause) {
        if (cause.isNetworkError()) {
            if (cause.getCause() instanceofSocketTimeoutException) {
                  /* your code here*/returnnewMyConnectionTimeoutException();
            } else {
                /* your code here*/returnnewMyNoConnectionException();
            }
        } else {
            //Do whatever you want to do if there is not a network error.  
        }
    }
}

Or you can create a custom Retrofit client that checks for connectivity before executing a request and throws an exception.

publicclassConnectivityCheckimplementsClient {

    Loggerlog= LoggerFactory.getLogger(ConnectivityCheck.class);

    publicConnectivityCheck(Client wrappedClient, NetworkConnectivityManager ncm) {
        this.wrappedClient = wrappedClient;
        this.ncm = ncm;
    }

    Client wrappedClient;
    private NetworkConnectivityManager ncm;

    @Overridepublic Response execute(Request request)throws IOException {
        if (!ncm.isConnected()) {
            log.debug("No connectivity %s ", request);
            thrownewNoConnectivityException("No connectivity");
        }
        return wrappedClient.execute(request);
    }
}

and then use it when configuring RestAdapter

RestAdapter.Builder().setEndpoint(serverHost)
                     .setClient(new ConnectivityCheck(new OkHttpClient(), ...))

Solution 2:

As far as I know, I don't think Retrofit supports 'connectivity checking in call time' and I don't think that is exactly what you want.

Try to check connectivity before your call, for example,

privatevoidsendData() {
    if( isConnected ) {
          switch(call) {
               case"userSignIn":
                      Call !
                      break;
               ...
    }
}

Maybe you can check this solution too

Post a Comment for "How To Catch The Exception In Retrofit Android"