How should I handle "No internet connection" with Retrofit on Android

Since retrofit 1.8.0 this has been deprecated

retrofitError.isNetworkError()

you have to use

if (retrofitError.getKind() == RetrofitError.Kind.NETWORK)
{

}

there are multiple types of errors you can handle:

NETWORK An IOException occurred while communicating to the server, e.g. Timeout, No connection, etc...

CONVERSION An exception was thrown while (de)serializing a body.

HTTP A non-200 HTTP status code was received from the server e.g. 502, 503, etc...

UNEXPECTED An internal error occurred while attempting to execute a request. It is best practice to re-throw this exception so your application crashes.


What I ended up doing is creating a custom Retrofit client that checks for connectivity before executing a request and throws an exception.

public class ConnectivityAwareUrlClient implements Client {

    Logger log = LoggerFactory.getLogger(ConnectivityAwareUrlClient.class);

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

    Client wrappedClient;
    private NetworkConnectivityManager ncm;

    @Override
    public Response execute(Request request) throws IOException {
        if (!ncm.isConnected()) {
            log.debug("No connectivity %s ", request);
            throw new NoConnectivityException("No connectivity");
        }
        return wrappedClient.execute(request);
    }
}

and then use it when configuring RestAdapter

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