有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用IOException包装非IOException

我正在尝试解决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包装非IOException安全吗
这样,应用程序就不会崩溃,只会将网络呼叫标记为失败

拦截器将如下所示:

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


共 (1) 个答案

  1. # 1 楼答案

    您不需要这样做,这显示了一个bug,在本例中,它可能在4.9.0中得到了修复。升级到3.149也应该修复它,但是在这种情况下它不再被支持,所以考虑采用4.90.

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

    如果异常是由代码引发的,则引发IOException是合适的做法,但OkHttp中的运行时异常会使其处于潜在的不一致状态(希望仍能工作)