RxJS to catch or not to catch

Sergey Gultyayev
1 min readDec 8, 2021

You need to show a toast when there is an error in the stream. It’s clear that you need to make it in catchError and then throwError . Wrong! Here is why.

While catchError is a great asset at your disposal you should be mindful when using it. Yes, if you re-throw the error in catchError it will be working, however, this is far from ideal.

There is a lesser-known feature of thetap operator that it has the same signature as subscribe callback. You can either provide next, error, complete callbacks as separate arguments (which is deprecated), or you can pass an object. This is where you should be handling most of the errors in the middle of a stream.

Nonetheless, you still need the catchError operator. When choosing between catchError and tap you need to consider two things:

  • if you need this stream to be intact when an error occurs
  • if you need to return to the stream a value when an error occurs

If your answer is YES for any of the items then catchError is your option to go. Otherwise, use the tap({error: () => {}}) for any logic like showing toasts etc. in middlewares like HttpInterceptors when you want to make some side effects that shouldn’t influence the stream in any way.

--

--

Sergey Gultyayev

A front-end developer who uses Angular as a main framework and loves it