Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping exception in RxJava 2

How can I map one occurred exception to another one in RxJava2? For example:

doOnError(throwable -> {
    if (throwable instanceof FooException) {
        throw new BarException();
    }
})

In this case I finally receive CompositeException that consists of FooException and BarException, but I'd like to receive only BarException. Help!

like image 720
piotrpawlowski Avatar asked Aug 25 '17 16:08

piotrpawlowski


People also ask

How to handle error in RxJava?

onErrorResumeNext. Once the onNext generates the first int after multiplying from 10 in map operator and when 2 comes up it throws the NPE Exception. It won't be moving to onError directly and the error would be handled in onErrorResumeNext and we can perform the rest actions in that.

What is Completable RxJava?

Single and Completable are new types introduced exclusively at RxJava that represent reduced types of Observable , that have more concise API. Single represent Observable that emit single value or error. Completable represent Observable that emits no value, but only terminal events, either onError or onCompleted.

What is flowable RxJava?

Flowable be the backpressure-enabled base reactive class. Let's understand the use of Flowable using another example. Suppose you have a source that is emitting data items at a rate of 1 Million items/second. The next step is to make network request on each item.


1 Answers

You can use onErrorResumeNext and return Observable.error() from it:

source.onErrorResumeNext(e -> Observable.error(new BarException()))

Edit

This test passes for me:

@Test
public void test() {
    Observable.error(new IOException())
    .onErrorResumeNext((Throwable e) -> Observable.error(new IllegalArgumentException()))
    .test()
    .assertFailure(IllegalArgumentException.class);
}
like image 139
akarnokd Avatar answered Oct 08 '22 15:10

akarnokd