Error-handling Operators

Delivering errors

As we’ve seen, when an error is encountered in a stream, RxJava delivers the error to the Observer via .onError(). Given that .onError() is terminal, no further processing will occur. However, this can be problematic, as programmer Dan Lew explains in his blog post:

Error Handling in RxJava

"I want to clear up something that many RxJava beginners get wrong: onError is an extreme event that should be reserved for times when sequences cannot continue. It means that there was a problem in processing the current item such that no future processing of any items can occur.

It’s the Rx version of try-catch: it skips all code between the exception and onError. Sometimes you want this behavior: suppose you’re downloading data then saving it to the disk. If the download fails, you want to skip saving. But what about if you’re, say, polling data from a source? If one poll fails you still want to continue polling. Or maybe, in the previous example, you want to save dummy data in the case that the download fails.

In other words: oftentimes, instead of calling onError and skipping code, you actually want to call onNext with an error state. It’s much easier to handle problems in onNext since you still get to run all your code and the stream isn’t terminated.

Indeed, depending on what we are processing, we might want to handle an error differently. We’ll look at the different error-handling-related operators that are available in RxJava."

Get hands-on with 1200+ tech skills courses.