我了解如何在不使用协程时处理错误:
@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)
}
}
最佳答案
为了处理调用 Retrofit 服务的 suspend
函数时的错误,请将其包装在 try-catch
block 中:
@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/