Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only catch exceptions of a specific type in RxJava 2

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));
like image 245
HolySamosa Avatar asked Feb 21 '17 15:02

HolySamosa


2 Answers

I would return Observable.empty instead just null

.onErrorResumeNext(t -> t instanceof NullPointerException ? Observable.empty():Observable.error(t))
like image 187
paul Avatar answered Sep 30 '22 16:09

paul


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.

like image 37
Tassos Bassoukos Avatar answered Sep 30 '22 18:09

Tassos Bassoukos