Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing an exception on subscription in RxJava

Tags:

java

rx-java2

Consider the following code :

  public static void main(String[] args) {
    try {
        observableTesting();
    } catch (Exception ex) {
        System.out.println("Exception propagated : " + ex.getLocalizedMessage());
    }
}


private static void observableTesting() throws Exception{
    Observable.fromCallable(() -> { throw new Exception("TEST"); })
            .subscribe(
                    next -> {},
                    error ->
                    {
                        System.out.println("Error : " + error.getLocalizedMessage());
                        throw new Exception(error);
                    }

            );}

I would expect this to throw an exception and to propagate it to the calling function. This doesn't seem to produce the desirable effect.

As a workaround, I currently have to assign the error and throw it at the end of the function.

Are there any better ways to convert observable errors into exceptions?

like image 662
achraf Avatar asked Dec 14 '25 23:12

achraf


1 Answers

It seem you're using rxjava-2. Under this version, the specification for errors state that all not handled Throwable will be delivered through either the Thread.UncaughtExceptionHandler installed on the system or the error handler installed via RxJavaPlugins.setErrorHandler(). If you're seeking to test the whether an observable throws or not, you can use TestObserver instead, as:

Observable
     .fromCallable(() -> { throw new Exception("TEST"); })
     .test()
     .assertSubscribed()
     .assertError(Exception.class);
like image 95
Jans Avatar answered Dec 16 '25 13:12

Jans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!