Reputation: 9241
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));
Upvotes: 6
Views: 6323
Reputation: 1215
if you need global error handling, you can use RxJavaPlugins
RxJavaPlugins.setOnObservableAssembly(observable -> {
if (observable instanceof ObservableError){
return observable.doOnError(throwable -> {
if(throwable instanceof SpecificException){
handleSpecificException();
}
});
}
return observable;
});
(Similar approach can be used for Singles, Maybes or Completables)
Upvotes: 1
Reputation: 13471
I would return Observable.empty instead just null
.onErrorResumeNext(t -> t instanceof NullPointerException ? Observable.empty():Observable.error(t))
Upvotes: 7
Reputation: 16152
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.
Upvotes: 6