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
Catch
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:
The 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.
Retries
With observables, you can retry the previous operation for a certain number of times, before the failure is fired.
##.finally() As JavaScript developers, our code deals with many events or asynchronous computations all the time. This can get complicated quickly as we build comprehensive UIs or state-machines that need to react and keep responsive in the face of failures. RxJS truly embodies two of the most important principles of the Reactive Manifesto, which are Responsive and Resilient.
Moreover, RxJS makes these computations first-class citizens of the language and offers a state-of-the-art event system for JavaScript. This provides a unified computing model that allows for readable and composable APIs to deal with these asynchronous computations, abstracting out the nitty gritty details of latency and wait time.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}