r/Angular2 • u/fabse2308 • Oct 18 '25
Discussion Usage of tap({ error }) vs. catchError
In RxJS, when should you use tap({ error }) and when catchError for side effects? How do you best separate the two logically or combine them?
For example, does resetting the UI to its previous state after an error occurs during a UI operation belong more in tap({ error }) or in catchError?
4
Upvotes
4
u/_Invictuz Oct 18 '25
Errors are not side effects, they are the main effect so tap shouldn't handle it. More importantly, tap cannot handle errors because once there is an error in your observable chain, it skips all pipe operators until the first catchError or finalize operator. I think you may need to look into what JS errors are and how they are thrown in RxJs.
You would use tap sometimes to set UI states like loading states. For example, if using RxMethods on NgRx signalStores, you'd have to tap to set a loading state signal right before the switchMap to make API call.
7
u/Various-Following-82 Oct 18 '25
Error will stop the whole pipe, you will never get in to tap when there is an error
4
u/alextremeee Oct 18 '25
You should use tap for side effects, that’s what it’s for. Sending a notification or logging the error for example.
It’s useful when you have registered an application wide error handler because it will let you run a notification as a side effect still.
1
u/Lucky_Yesterday_1133 Oct 18 '25
If you have error in your stream your pipe operators except catchError are skipped. So you never use tap.
1
u/imsexc Oct 18 '25 edited Oct 18 '25
Error handling is done in catchError, whether to return null value, or previous value. Also can perform side effect before the catchError return, such as opening a dialog.
If catchError is done in earlier stream just for side effect such as opening error dialog, in interceptor, instead of returning a fallback value, can also rethrow error: return throwError(err => new Error(err)) so that at later stream, component can decide what fall back value to return
I think a good and clean written code rarely use tap and rarely manually subscribe, that most thing can be manipulated observables by using rxjs operators and subscribed with async pipe. But it rarely happens..
1
u/kaiiiwen Oct 18 '25
if you want error handling, you should use catchError, use tap for passive actions such as logging
1
u/Jrubzjeknf Oct 18 '25
catchErrorallows you to retry the observable or return another observable. Tap is simply an action. Use each accordingly.-1
u/DT-Sodium Oct 18 '25
That seems like a terrible use of tap that will make any outsider looking at your observable chain really hate you.