我们的应用程序有许多网络请求,我们正在使用带有 Retrofit 的协程,如下所示:
suspend fun fetchAccountInfo() {
val api = retrofit.create(MainActivityApi::class.java)
val versionResponse = api.getVersionAsync().await()
...
}
问题是,当设备未连接到互联网时,Retrofit 会抛出异常,应用程序将崩溃。我发现这个链接说,将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中的情况下防止应用程序崩溃?
虽然包装是首选方法,但我相信还有另一种方法(我个人不会使用它,但可能适合你)
您可以创建一个 OkHttp 拦截器,它将对每个请求进行尝试捕获,并返回由 Retrofit 的静态 Response.error(someParams) 创建的响应。
可以参考https://github.com/gildor/kotlin-coroutines-retrofit/issues/34进行构建,基本上只需更改catch{}块即可。
希望这有帮助,GL!
正如另一条评论已经提到的,您可以创建一个自定义拦截器来处理异常并返回指示错误的自定义响应。
class TeapotInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val response: Response = try {
chain.proceed(request)
} catch (e: Exception) {
// Log here
Response.Builder()
.request(request)
.protocol(Protocol.HTTP_2)
.code(418)
.message("I'm a teapot")
.build()
}
return response
}
}
val teapotInterceptor = TeapotInterceptor()
OkHttpClient.Builder()
.addInterceptor(teapotInterceptor)
.build()