简体   繁体   中英

How to get API error body using Kotlin coroutines

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

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 ...
         }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM