Aal*_*tel 3 java error-handling android rx-android rx-java2
所以我有一个非常基本的 RxJava 观察者流工作流程,我从改造中请求一些东西,如果响应成功,我会烘烤成功的消息,如果出现错误,我会烘烤错误消息。
我下面提到的情况是错误情况,我期望来自 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();
Run Code Online (Sandbox Code Playgroud)
错误如果这还不够,我也可以发布堆栈跟踪。
java.lang.IllegalStateException: Exception thrown on Scheduler.Worker thread. Add `onError` handling.
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
但同样的事情,我以这种方式订阅,它工作正常,我看到错误消息按预期烤。
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);
});
Run Code Online (Sandbox Code Playgroud)
还是 RxJava2 世界的新手,请帮助我理解其中的区别。先感谢您。
从 RxJava 2.1.9 开始,有六种方法重载subscribe()。您使用了重载,根本不需要任何消费者。异常消息告诉您,您应该使用subscribe()带有 error 的重载Consumer,例如subscribe(Consumer<? super T> onNext, Consumer<? super java.lang.Throwable> onError)。
doOnError()是一个“副作用”运算符,它与实际订阅无关。
| 归档时间: |
|
| 查看次数: |
3089 次 |
| 最近记录: |