It seems that there are two kinds of error in RxJava:
- Errors caught by a subscriber in
onError - And errors caught globally by the handler set by
RxJavaPlugins.setErrorHandler
I am having some trouble understanding why this is. Questions:
- What was the rationale behind having two handlers for errors?
- What causes an error to be sent to one handler vs the other?
- How can I ensure that errors are only sent to
onError?
2 Answers
You can find most of the design decisions on the Wiki pages for changes done for Rx2:
One important design requirement for 2.x is that no
Throwableerrors should be swallowed. This means errors that can't be emitted because the downstream's lifecycle already reached its terminal state or the downstream cancelled a sequence which was about to emit an error.
To ensure that errors are only handled by the onError() consumer of the observer, you'd have to set the global handler to an empty consumer:
RxJavaPlugins.setErrorHandler(emptyConsumer()); Subscribe onError() handles the errors that are emitted before the stream reaches its terminal state. For errors emitted after the stream terminates or after it gets cancelled rxjava defaults to printing the stacktrace to the console and calling the uncaught exception handler i.e crashing. RxJavaPlugins.setErrorHandler(...) therefore is necessary to handle these undeliverable exceptions on a global scope.
Reference: