我有一个从改造中生成的可观察值,我正在尝试对其实现错误处理,特别是连接超时。出错的订阅者被调用得很好,但应用程序仍然因套接字超时错误而崩溃。有什么建议吗?
Observable<History> history = api.returnHistoryRX(pair, String.valueOf(unixTime-3600), String.valueOf(unixTime));
history.onErrorReturn(throwable -> null);
订阅者
public void getPriceNow(Observable<List<history>> history, String pair) {
Timestamp timestamp2;
timestamp2 = new Timestamp(System.currentTimeMillis());
history.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(history1 -> {
String currentValue;
if (history1.size()>0){
System.out.println("testing rx");
}
}, e->System.out.println("getPriceNow: error called"));
}
为了测试,我使用 okhttp 将超时设置为不合理的低
private OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.MILLISECONDS)
.readTimeout(30L, TimeUnit.MILLISECONDS)
.writeTimeout(100L, TimeUnit.MILLISECONDS);
错误链如下所示:
java.lang.IllegalStateException:在 Scheduler.Worker 线程上抛出异常。添加 onError
处理。
原因:rx.exceptions.OnErrorNotImplementedException:连接失败
原因:java.net.SocketTimeoutException:连接失败
最佳答案
当您调用 history.onErrorReturn(...)
时,该方法会返回一个应用了适当行为的 new Observable
。您需要在想要应用错误处理行为的地方使用返回的可观察值。在你的情况下,它可能就像改变一样简单
history.onErrorReturn(throwable -> null);
到
history = history.onErrorReturn(throwable -> null);
或将其移动到初始化 history
变量的位置。
关于android - rxJava 捕获 socketTimeoutException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41403424/