A simple way to handle API error payload with Retrofit the same way as the success one.
It is very easy to use Retrofit for calling API and converting successful responses to a model. However, it becomes a bit less trivial when it comes to error responses. For instance, validation error after submitting a form. Retrofit threats such cases as exceptions and will throw HttpException in that case.
retrofit2.HttpException: HTTP 400 Bad Request
So, it is needed to catch it, get a payload, and convert it to a desired model. Not terrible, but might be better, probably.
Ideally, it would’ve been nice to make Retrofit handle payloads of error responses the same way as success ones. So there is either a success model or an error model. Luckily, it can be achieved by using an Either type from arrow-kt library, and an EitherCallAdapterFactory that will tell Retrofit how to use it. Eventually, an API method will look like this:
@PUT("sign-up") suspend fun signUp( email: String, password: String, ): Either<ErrorResponse, SuccessResponse>
Later on, such Either result can be “folded” via .fold(::ifLeft, ::ifRight) and process either of the cases however needed.
More details can be found in the sample app on GitHub.
Consider checking other parts of Arrow-Kt.
Originally published on Medium by Pavel Vashkel.
Check out our newsletter