Up until now, you’ve learned different types of asynchronous operations on streams, whether they be on DOM events or fetching remote data. But none of the examples so far have shown you what happens when there’s an error or an exception in the stream pipeline. DOM events are very easy to work with because they won’t actually throw errors. The same can’t be said about AJAX calls. When not dealing with simple arrays, streams are actually highly unpredictable and you must be prepared for the worst.
With errors, if you are passing your own observer, you need to try
catch inside and call
observer.onError(error); This will allow you to catch the error , handle it, and also dispose.
Alternatively, you can use .onErrorResumeNext
The good news is that you can continue to use a good ’ol
catch block (now an operator) just like you’re used to. To show this I’ll artificially create an error as soon as a stream sees the value 5.
As soon as the condition is met, the exception is thrown and propagated all the way down to the Observer subscribed to this stream. You might want to gracefully catch the exception and provide a friendly message:
catch operator allows you to handle the error so that it doesn’t get propagated down to any observers attached to this stream. This operator expects another Observable to carry the baton forward, so you can use this to suggest some default value in case of errors. Notice that, this time, the error function on the observer never actually fired!
Now, if we do want to signal an unrecoverable condition, you can catch and throw the error. Within the catch block, this code will actually cause the exception to fire. I would caution against this as throwing exceptions is a side effect that will ripple through and is expected to be handled somewhere else. This should be used sparingly in truly critical conditions.
Another option is to attempt a retry.
With observables, you can retry the previous operation for a certain number of times, before the failure is fired.