API 关闭时改造 SocketTimeoutException 错误

Retrofit SocketTimeoutException Error When API is Down

我正在尝试创建一个 Interceptor 以防我正在使用的 API 出现故障,这发生在我尝试进行 API 调用时邮递员只为它 return 一个 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 添加什么,或者我应该在 try catch 语句中包围我的 execute() 调用?

正确的解决方案是使用 enqueue 而不是 executesynchronous 网络调用几乎总是一个坏主意,因为您不想阻塞调用线程。要使用 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,那么至少您必须将执行调用包含在 try catch

try{
    call.execute()
}
catch(e: Exception){
     // Process any received exception (SocketTimeOutEtc)
}