Handle Retrofit Success and Error responses like a pro
Welcome folks, so nice to see you here again,
Today we will learn how to handle various api responses in retrofit with a breeze!!
You might want to read my previous article on using Retrofit with MVVM architecture, This article will be based upon some of the techniques we have used there
https://shivamk345.medium.com/retrofit-fetch-api-with-clean-architecture-mvvm-cc95a0f7f6f
Let's create an api interface
Now create an interface for our profile different use cases like here, we are using to get profile data of the user
Now we will handle retrofit success and error responses, which means we will get a response with a code of 201 and 501 or 404
As you might already know we get successful responses in codes 201 or 200 and on errors we get 501 or 404
Now let's assume our error response look like below
So for this, we need to create an error response model class to model JSON response into the kotlin object
Now our helper class in which we will pass api response and handle cases for the results,
We will success result in Resouce.Success(data) and Resouce.ErrorResponse(errorObject)
Let's see the implementation here
As you can see we are handling api error cases in else block in the above method, This important method is this
Constant.getErrorResponse(response.errorBody()!!.string())
Constant is an static helper class, I mainly use it for creating methods which will be used in all screens of the app like showing toast message or dialog
Here we are getting our error json response which is converted into a string by response.errorBody()!!.string()
Now we need to convert this String into our custom object class ErrorResponse
Now time to use our simple but powerful implementation which will make our life a lot easier
Now using our ViewModel in our main UI Activity or Fragment
Congrats! You have handle retrofit two main responses like a pro
Stay tuned for more