【发布时间】: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