gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:04:29 27 4
gpt4 key购买 nike

我正在尝试使用改造和协程来执行 POST 请求,每当 HTTP 响应状态不是 200 时,它就会抛出异常。我的 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"
}

我想在没有回调的情况下捕获此错误消息,这可能吗?

API服务类

@GET("flowers")
suspend fun getAllFlowers(@Query("page") page: Int): Flowers

@POST("users/register")
suspend fun registerUser(@Body user: User) : NetworkResponse

网络响应类

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

View 模型类

     fun registerUser(user: User) {
coroutineScope.launch {
try {
val registerUser = FlowerApi.retrofitService.registerUser(user)
_token.value = registerUser.auth
} catch (cause: Throwable) {
//CATCH EXCEPTION
}
}
}

提前致谢

最佳答案

在您的 catch block 中,您需要检查 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 ...
}
}
}

关于android - 如何使用 Kotlin 协程获取 API 错误主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63223917/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com