首页 > 解决方案 > 用 IOException 包装非 IOExceptions

问题描述

我正在尝试解决 okhttp 内部异常(以及任何其他可能的运行时异常):

java.util.NoSuchElementException: 
at okhttp3.internal.connection.RouteSelector.next()(RouteSelector.java:75)
at okhttp3.internal.connection.ExchangeFinder.findConnection()(ExchangeFinder.java:187)
at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection()(ExchangeFinder.java:108)
at okhttp3.internal.connection.ExchangeFinder.find()(ExchangeFinder.java:88)
at okhttp3.internal.connection.Transmitter.newExchange()(Transmitter.java:169)
at okhttp3.internal.connection.ConnectInterceptor.intercept()(ConnectInterceptor.java:41)
at okhttp3.internal.http.RealInterceptorChain.proceed()(RealInterceptorChain.java:142)
...

添加拦截器并用 IOException 包装非 IOExceptions 是否安全?
这样,应用程序不会崩溃,只是网络调用将被标记为失败。

拦截器看起来像这样:

public class WrapExceptionsInterceptor implements Interceptor {
@NonNull
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
    try {
        return chain.proceed(chain.request());
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(e);
    }
}

我只是担心这是否会使 OkHttpClient 处于无效状态?

改造版本:2.9.0
okhttp 版本:3.14.0

标签: javaandroidretrofitokhttp

解决方案


您不需要这样做,这显示了一个错误,在这种情况下可能已在 4.9.0 中修复。升级到 3.14.9 也应该可以修复它,但在这种情况下它不再受支持,因此请考虑采用 4.9.0。

https://github.com/square/okhttp/issues/5605

如果异常是由您的代码引发的,那么引发 IOException 将是适当的做法,但是 OkHttp 中的运行时异常会使其处于潜在的不一致状态(希望仍然可以正常工作)。


推荐阅读