Reputation: 26034
I'm learning RxJava and I have seen in many places that an error can be handled this way:
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>
; you can't use your own base exception, just Throwable
.
Upvotes: 3
Views: 997
Reputation: 16142
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))))
....
Upvotes: 6