This post is about handling errors in RxJs. We’ll dive into when and how you’d handle them using the following three Operators that RxJs provides:

  • catchError
  • retry
  • retryWhen

Without further delay, lets jump right in.

Note: _You can find all of the code examples in this Git repository

What happens when an error occurs

As we covered in the last post, an Observable emits a stream of values. While emitting values, an error might occur and be emitted. The Observer should be able to handle any errors that get emitted.

But once the Observable emits an error the stream will be terminated and no further items will be emitted. If the stream is terminated the application would need some way to handle that or it’ll crash.

One of the core principles in Reactive Programming is that the application should be resilient. Meaning, we should be able to handle errors before they reach the Observer. Because, if the error function is invoked on the Observer it means the stream is terminated.

It’s too late.

So, is there a way to intercept the error before it gets to the Observer and do something about it in a way that the stream won’t be terminated? Or, even if the stream is terminated, is there a way to switch over to one that’s available?

You guessed it. The catchError(), retry() and retryWhen() Operators allow us to handle errors in different ways and depending on your use case you can use one or a combination of these Operators.

Lets look at each one in detail.

#web-development #programming #javascript #rxjs #developer

3 Ways To Handle Errors in RxJs
2.15 GEEK