Kotlin is a great language to start learning android development, and tbh after using kotlin everything else feels like a downgrade.
One of the best futures of kotlin is coroutines and using them with retrofit calls can make your code not only abstract and simple but also pretty to look at !
But one of the main challenges i faced when making retrofit calls with coroutines is error handling as the structure that u get from the error response is different than the successful response, also simply calling response.errorBody() won’t work and returns null, here’s how to properly get the error response and convert it to your ResponseError data class.
so baiscally what we are doing here is getting the error response as a string by calling Response.errorBody().string() NOT .toString()
then using a Gson object to convert the string to a ResponseError object, from here we can easily get the message from the error body using errorResponse.error.message (or whatever your variable of the error message is named)
One thing u should avoid here is calling response.errorBody().string() twice as the second time it’ll return an empty string because its a resource that will be gone once you call it the first time
Also don’t worry about android studio giving “Inappropriate blocking method call” warning on the .string() method as its a false positive
Happy Coding 🙂