java - 用 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
解决方案
您不需要这样做,这显示了一个错误,在这种情况下可能已在 4.9.0 中修复。升级到 3.14.9 也应该可以修复它,但在这种情况下它不再受支持,因此请考虑采用 4.9.0。
https://github.com/square/okhttp/issues/5605
如果异常是由您的代码引发的,那么引发 IOException 将是适当的做法,但是 OkHttp 中的运行时异常会使其处于潜在的不一致状态(希望仍然可以正常工作)。
推荐阅读
- docker - “docker ps -a”是什么意思?
- javascript - 如何克隆反应子组件并修改其文本?
- python - 我们可以用python生成器读取pickle文件中的数据吗
- javascript - 一种更惯用的编写庇护管道的方式
- r - 如何使用 R as.POSIXct 处理混合精度日期
- python - 使用 Bokeh 对数刻度的上标指数
- apache - Certbot /letsencrypt 生成 [www] 证书后 [non-www] 域出错
- firebase - 使用 REST API 在 Firebase 中删除帐户/用户
- vba - 防止有条件的数据重复
- azure-maps - 在 Azure Maps 中引入新的(预览)天气切片图层的正确 url 格式是什么?