gpt4 book ai didi

android - 使用 Kotlin 协程对 Retrofit2 进行错误处理

转载 作者:行者123 更新时间:2023-12-03 08:40:12 24 4
gpt4 key购买 nike

我了解不使用协程时如何处理错误:

@GET("user/{user}")
fun getHomeData(@Path("user") user: String?): Call<HomeDataBody>



fun getHomeData(id:String, callback: (Boolean, String?) -> Unit)
{
val call = service.getHomeData(id)
call.enqueue( object : Callback<HomeDataBody> {
override fun onResponse(call: Call<HomeDataBody>, response: Response<HomeDataBody>)
{
if (response.isSuccessful)
{
dataMgr.homeData = response.body()!!.user

callback(true, null)
}
else
{
callback(false, response.message())
}
}

override fun onFailure(call: Call<HomeDataBody>, t: Throwable)
{
callback(false, t.message)
}

})
}

但是我一生都无法弄清楚如何使用协程来做到这一点,这就是我对不返回错误的协程所做的:
@GET("user/{user}")
suspend fun getHomeDataCoroutine(@Path("user") user: String?): HomeData


suspend fun getHomeDataCoroutine(id:String) : Pair<Boolean, String>
{
val data = service.getHomeDataCoroutine(id)

if(data != null)
{
dataMgr.homeData = data
}
else
{
return Pair(false, "how do i get the error message??")
}

}

我也尝试过这个,但是当我尝试调用 service.getHomeDataCoroutine 时出现此错误:
java.lang.IllegalArgumentException:无法为类 java.lang.Object 创建调用适配器
对于方法 RiseServiceRetro.getHomeDataCoroutine
@GET("user/{user}")
suspend fun getHomeDataCoroutine(@Path("user") user: String?): Deferred<HomeDataBody>?

sealed class Result<out T : Any>
class Success<out T : Any>(val data: T) : Result<T>()
class Error(val exception: Throwable, val message: String = exception.localizedMessage) : Result<Nothing>()

suspend fun getHomeDataCoroutine(id:String): Result<HomeDataBody>
{
try {
val response = service.getHomeDataCoroutine(id)!!.await()
return Success(response)
} catch (e: Exception) {
return Error(e)
}

}

最佳答案

在调用 suspend 时处理错误Retrofit 服务的功能包裹在 try-catch堵塞:

@GET("user/{user}")
suspend fun getHomeDataCoroutine(@Path("user") user: String?): HomeDataBody

suspend fun getHomeDataCoroutine(id:String): Pair<Boolean, String> {
return try {
val data = service.getHomeDataCoroutine(id)
dataMgr.homeData = data
Pair(true, "")
} catch(e: Throwable) {
Pair(false, e.message ?: "error")
}
}

关于android - 使用 Kotlin 协程对 Retrofit2 进行错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62233554/

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