所以我有一个非常基本的 RxJava 观察者流工作流程,我从改造中请求一些东西,成功响应我 toast 成功消息,错误消息我 toast 错误消息。
我在下面提到的情况是我期望来自 API 的错误消息的错误情况,我将其转换为用户可读的单词并显示为 Toast
,如下所示,当我使用 doOnNext
和 doOnError
方法,它会因提到的错误而崩溃。
我还添加了 throwExceptionIfFailure
方法,它显示了我如何转换可读消息以及控制台指向错误的行。
registerNFCTag(body)
.map(result -> throwExceptionIfFailure(result))
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(result -> {
toggleLoaders(true);
appToast(getString(R.string.done_msg) + tagName);
})
.doOnError(throwable -> {
Toasty.error(this, throwable.getLocalizedMessage()).show();
toggleLoaders(true);
})
.subscribeOn(Schedulers.io())
.subscribe();
错误如果这还不够,我也可以发布堆栈跟踪。
java.lang.IllegalStateException: Exception thrown on Scheduler.Worker thread. Add `onError` handling.
ThrowExceptionIfFailure 方法。
public <T> T throwExceptionIfFailure(T res) {
Response result = (Response<?>) res;
if (!result.isSuccessful()) {
try {
String msg = result.errorBody().string();
Log.d(TAG, "throwExceptionIfFailure: "+msg);
if (result.code() == 401 || result.code() == 403) {
invalidateToken();
msg = context.getString(R.string.invalid_credential);
}
else if (result.code() == 502)
msg = context.getString(R.string.server_down);
else if (result.code() == 422)
msg = context.getString(R.string.invalid_domain);
else if (result.code() == 500)
msg = context.getString(R.string.internal_server_error_500_msg);
else if (result.code() == 451)
------><>>>>>> expected error msg works well with the case mentioned below with throwable in subscribe itself.
msg = context.getString(R.string.toast_tag_already_registered_error);
if (result.code() == 403)
throw new TokenException();
else
------>>>>>below line where console points error
throw Exceptions.propagate(new RuntimeException(msg));
} catch (Throwable e) {
throw Exceptions.propagate(e);
}
} else {
return res;
}
}
但同样的事情我以这种方式订阅并且它工作正常并且我看到错误消息按预期烘烤。
registerNFCTag(body)
.map(result ->throwExceptionIfFailure(result))
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(
result -> {
toggleLoaders(true);
appToast(getString(R.string.done_msg) + tagName);
}
, throwable -> {
Toasty.error(this, throwable.getLocalizedMessage()).show();
toggleLoaders(true);
});
还是 RxJava2 世界的新手所以,帮助我理解其中的区别。先感谢您。
最佳答案
从 RxJava 2.1.9 开始有 six overloads的 subscribe()
方法。您使用了一个过载,它根本不需要任何消费者。异常消息告诉您,您应该使用 subscribe()
过载,出现错误 Consumer
,例如 subscribe(Consumer<? super T> onNext, Consumer<? super java.lang.Throwable> onError)
.
doOnError()
是一个“副作用”运算符,它与实际订阅无关。
关于java - onError 未在 RxJava2 中实现错误,即使它已实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46739840/