Detect offline error in Retrofit 2
Displaying ‘no internet connection’ error is quite a common requirement. The sample below demonstrates how to make Retrofit 2 throw ‘no internet connection’ exception.
Essentially, you’ll create a class that implements Interceptor so that you can perform a network connectivity check before executing the request.
ConnectivityInterceptor.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class ConnectivityInterceptor implements Interceptor { private Context mContext; public ConnectivityInterceptor(Context context) { mContext = context; } @Override public Response intercept(Chain chain) throws IOException { if (!NetworkUtil.isOnline(mContext)) { throw new NoConnectivityException(); } Request.Builder builder = chain.request().newBuilder(); return chain.proceed(builder.build()); } } |
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.
NetworkUtil.java
1 2 3 4 5 | public static boolean isOnline(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo(); return (netInfo != null && netInfo.isConnected()); } |
NoConnectivityException.java
1 2 3 4 5 6 7 8 | public class NoConnectivityException extends IOException { @Override public String getMessage() { return "No connectivity exception"; } } |
Creating a custom Exception class allows us to catch it by Exception class type for error handling.
When instantiating a Retrofit service,
1 2 3 4 5 6 7 8 9 10 | OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new ConnectivityInterceptor(context)) .build(); MyRetrofitService service = new Retrofit.Builder() .baseUrl("https://example.com) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build() .create(MyRetrofitService.class); |
In try-catch block for Retrofit web service failure,
1 2 3 | if (exception instanceof NoConnectivityException) { // No internet connection } |