简体   繁体   English

如何使用 Kotlin 协程获取 API 错误主体

[英]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.我正在尝试使用 retrofit 和协程进行 POST 请求,每当 HTTP 响应状态不是 200 时,它只会引发异常。 My API has a response body that looks like this:我的 API 的响应正文如下所示:

{
 "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 Api 服务 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

 class NetworkResponse(
   val auth: String,
   val error:  String)

ViewModel class查看型号 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块中,您需要检查throwable是否是HttpException (来自 Retrofit 包),然后您可以通过调用cause.response()?.errorBody()?.string()从中找到错误正文:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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