Android 应用程序在改造拦截器中因 SocketTimeoutException 而崩溃

问题描述

以下是我的离线拦截代码。它在低网络的情况下崩溃并抛出 SocketTimeoutException。在这种情况下如何避免应用程序崩溃?

internal class CacheOfflineInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val offlineCacheDuration = request.header(MAX_STALE_IN_DAYS)
        if (!isOnline && offlineCacheDuration != null) {
            val maxStale = 60 * 60 * 24 * offlineCacheDuration.toLong()

            request = request.newBuilder()
                    .removeHeader(PRAGMA)
                    .header(CACHE_CONTROL,"private,max-stale=$maxStale")
                    .build()
        }

        try {
            val response = chain.proceed(request)
            return response
        } catch (e: Throwable) {
            if (e is IOException) {
                throw e
            } else {
                throw IOException(e)
            }
        }
    }
}

我在低网络情况下遇到以下异常

Fatal Exception: java.net.socketTimeoutException: Failed to connect to /192.168.0.110 (port 8888) from /192.168.0.159 (port 49025) after 10000ms
       at libcore.io.IoBridge.connectErrno(IoBridge.java:185)
       at libcore.io.IoBridge.connect(IoBridge.java:130)

解决方法

当某些事情失败时,您将在 Exception 中抛出一个 Interceptor,这会将 Exception 一直抛出到 Caller,为了避免崩溃,您需要在某个级别处理此 Exception,您可以在 interceptor 中抑制它并记录它以供参考(或)您可以只处理调用者链中的异常。