I am trying to do POST request with retrofit and coroutines, and whenever the HTTP response status is not 200, it just throws an exception. My API has a response body that looks like this:
{
"auth_token": null,
"error": "Email can't be blank. Password can't be blank. First name can't be blank. Last name can't
be blank. Date of birth can't be blank"
}
I want to catch this error message WITHOUT CALLBACKS, is that possible ?
Api service class
@GET("flowers")
suspend fun getAllFlowers(@Query("page") page: Int): Flowers
@POST("users/register")
suspend fun registerUser(@Body user: User) : NetworkResponse
Network response class
class NetworkResponse(
val auth: String,
val error: String)
ViewModel class
fun registerUser(user: User) {
coroutineScope.launch {
try {
val registerUser = FlowerApi.retrofitService.registerUser(user)
_token.value = registerUser.auth
} catch (cause: Throwable) {
//CATCH EXCEPTION
}
}
}
Thanks in advance