android - 当 API 关闭时改造 SocketTimeoutException 错误

标签 android kotlin retrofit retrofit2 okhttp

我正在尝试创建一个拦截器,以防我正在使用的 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/

相关文章:

android - API 小于 21 的点击波纹效应

android - 从 retrofit2 和 rxjava 中的错误中获取 url

java - 无法读取 rss XML,使用简单 XML 和 Retrofit

android - 如何在 recyclerview 中只加载新图像而不加载旧图像?

android - 从 SQLite 数据库 Android SDK 中获取随机行

android - 如何在对话框中添加多个 TextView

android - 如何将 Room TypeConverter 应用于实体的单个字段?

java - 使用改造发送带有一些参数的多部分(文件)

android - setFragmentResult 在单击监听器上不起作用

android - 在使用 recyclerView 填充的 cardView 中为按钮添加点击监听器