3

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

Stack Fox
  • 1,201
  • 9
  • 14

1 Answers1

0

Inside your catch block you need to check if the throwable is an HttpException (from Retrofit package) and then you can find the error body from it by calling cause.response()?.errorBody()?.string():

catch (cause: Throwable) {
    when (cause) {
         is HttpException -> { 
              cause.response()?.errorBody()?.string() //retruns the error body
         }
         else -> {
              //Other errors like Network ...
         }
    }
}
Ehsan Heidari
  • 486
  • 6
  • 17