我正在尝试创建一个拦截器,以防我正在使用的 API 出现故障,这种情况发生在我尝试在 Postman 上进行 API 调用以使其返回一个504
错误。
这是我现在拥有的OkHttpClient
。我将其设置为 5 秒只是出于测试目的。
val client = OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.addInterceptor(object : Interceptor {
override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
val response = chain.proceed(chain.request())
when (response.code()) {
504 -> {
//Show Bad Request Error Message
}
}
return response
}
})
.build()
searchRetrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(URL)
.client(client)
.build()
在代码的后面,我使用 Retrofit 的 execute()
方法对 API 进行同步调用。如果 API 服务关闭或检索时间过长,execute()
行和 val response = chain.proceed(chain.request())
会使我的应用程序崩溃结果。我收到 java.net.SocketTimeoutException
错误。
当我使用的 API 服务关闭时,我可以采取什么措施来防止我的应用程序崩溃?我可以向 Interceptor
添加什么内容,还是应该将 execute()
调用包含在 try catch
语句中?
最佳答案
正确的解决方案是使用 enqueue
而不是执行
。同步网络调用几乎总是一个坏主意,因为您不想阻塞调用线程。要使用enqueue
,你应该这样做
call.enqueue(object : Callback<SomeResponse> {
override fun onFailure(call: Call<SomeResponse>?, t: Throwable?) {
// This code will be called when your network call fails with some exception
// SocketTimeOutException etc
}
override fun onResponse(call: Call<SomeResponse>?, response: Response<SomeResponse>?) {
// This code will be called when response is received from network
// response can be anything 200, 504 etc
}
})
如果您必须使用execute
,那么至少您必须将您的execute调用包含在try catch
中
try{
call.execute()
}
catch(e: Exception){
// Process any received exception (SocketTimeOutEtc)
}
关于android - 当 API 关闭时改造 SocketTimeoutException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68492176/