Retrofit 2— Best way for Handling Network Error

Getting bored to check internet connectivity before each network call again and again ? Use Interceptor with Retrofit Service Client.

SHISHIR
PROGRAMMING LITE
2 min readOct 16, 2018

--

Image result for Retrofit 2

This is a common practice for most of the developers to have a network check before each and every API call. I also did the same and i got bored. Then i started looking for an optimal way. And finally i got the solution by adding an Interceptor with okhttpClientBuilder.

Workflow of Handling Network Error:

  • Create a class NetworkConnectionInterceptor . And override the method intercept(Chain chian) to check internet connection availability inside it.

Now if we add this NetworkConnectionInterceptor interceptor with Retrofit Service client, it will handle every API call. Before each and every API call intercept(Chain chain) method will be called and it will check for internet connectivity. If no network found then it will interrupts the normal flow of execution and throw NoConnectivityException exception. The exception class looks like below.

  • So add NetworkConnectionInterceptor interceptor with your retrofit Service client.
  • Finally, catch the exception in onFailure(Call<BaseModel> call, Throwable e) or onError(Throwable e) method and show the network error message to user.

That’s it. You have done. !!!!!!!!!!

While working with Retrofit we sometimes face some issues. If you want to handle those you can see my another article Retrofit 2 — Handling Some Cases.

To keep API Keys secured in your app you can see my article Securing API Keys in Android APP.

Thanks for reading this article. Be sure to give claps if you find this article helpful.

Happy Coding :)

--

--

SHISHIR
PROGRAMMING LITE

{ 'designation' : 'Lead Software Engineer' , 'hobby' : [ 'Music', 'Photography', 'Travelling' ] ,’email’: ‘shishirthedev@gmail.com’ }