【问题标题】:How to deal with exception with Deferred await error in Retrofit如何处理 Retrofit 中延迟等待错误的异常
【发布时间】:2019-05-14 12:32:23
【问题描述】:

我们的应用程序有很多网络请求,我们正在使用带有 Retrofit 的协程,如下所示:

suspend fun fetchAccountInfo() {
    val api = retrofit.create(MainActivityApi::class.java)
    val versionResponse = api.getVersionAsync().await()
    ...
}

问题是当设备没有连接到互联网时,Retrofit 会抛出异常并且应用程序会崩溃。我发现this link 说,将 await() 放入这样的 try/catch 中:

suspend fun fetchAccountInfo() {
    val api = retrofit.create(MainActivityApi::class.java)
    try {
        val versionResponse = api.getVersionAsync().await()
    } catch(e: Exception) {
      //
    }
    ...
}

但是我们的应用有很多网络请求,这个解决方案不适合我们。如何在不将所有 await() 调用放入 try/catch 的情况下防止应用程序崩溃?

【问题讨论】:

    标签: android kotlin retrofit2 coroutine


    【解决方案1】:

    尽管包装是首选方法,但我相信还有另一种方法(我个人不会使用它,但可能适合你)

    您可以创建一个 OkHttp 拦截器,它会对每个请求进行尝试捕获,并返回由改造的静态 Response.error(someParams) 创建的响应。

    你可以参考https://github.com/gildor/kotlin-coroutines-retrofit/issues/34的构造,你基本上只需要改变catch{}块。

    希望这会有所帮助,GL!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-29
      • 2018-07-29
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 2018-11-12
      • 2022-01-09
      • 2018-04-06
      相关资源
      最近更新 更多