I'm just learning RxJava 2 and I would like catch exceptions only of a specific type and return an Observable. Essentially, I want onErrorResumeNext()
to only catch a specific exception class, but it looks like she doesn't work that way.
What are my options for achieving this behavior in RxJava 2? Just use onErrorResumeNext()
, handle my specific exception and rethrow the others? Something like:
.onErrorResumeNext(throwable -> throwable instanceof NotFoundException ? Observable.empty() : Observable.error(throwable));
I would return Observable.empty instead just null
.onErrorResumeNext(t -> t instanceof NullPointerException ? Observable.empty():Observable.error(t))
Just use composition:
public <T> Function<Throwable, Observable<T>> whenExceptionIsThenIgnore(Class<E> what) {
return t -> {
return what.isInstance(t) ? Observable.empty() : Observable.error(t);
};
}
Then use like this:
Observable.from(...).flatMap(...)
.onErrorResumeNext(whenExceptionIsThenIgnore(IllegalArgumentException.class))
.onErrorResumeNext(whenExceptionIsThenIgnore(IOException.class))
...
See also this answer on selectively handling exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With