[英]Looking for a clean way to handle errors in RxJava
I'm learning RxJava and I have seen in many places that an error can be handled this way: 我正在学习RxJava,并且在许多地方看到可以通过这种方式处理错误:
repository.getById(10).subscribe(new Action1<User>() {
@Override
public void call(User user) {
//Do something
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable t) {
if (t instanceof FirstErrorException) {
handleFirstError((FirstErrorException) t);
} else if (t instanceof FirstErrorException) {
handleSecondError((SecondErrorException) t);
} else {
//and so on...
}
}
});
Am I the only one that thinks that this is really bad code? 我是唯一认为这确实是错误代码的人吗? How can I make it better?
我怎样才能做得更好? I though using
Visitor
pattern that "visits" each concrete type of my base exception, but onError
method always requires an Action1<Throwable>
; 我虽然使用了
Visitor
模式来“访问”我的基本异常的每种具体类型,但是onError
方法始终需要Action1<Throwable>
; you can't use your own base exception, just Throwable
. 您不能使用自己的基本异常,而只能使用
Throwable
。
Error handlers to the rescue: 错误处理程序:
<T,E extends Throwable> Observable<T>
whenExceptionIs(Class<E> what, Func1<E,Observable<T>> result) {
return t -> {
return what.isInstance(t) ? result.call(t) : Observable.error(t);
};
}
This you use like this: 您可以这样使用:
Observable<Foo> obs = ...
.onErrorResumeNext(whenExceptionIs(IllegalArgumentException.class, t-> Observable.just(Foo.newInstance())))
.onErrorResumeNext(whenExceptionIs(IOException.class, t-> Observable.error(new XyzzyException("",t))))
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.