Not too long ago, I wrote a post on Global Error Handling in Angular. The gist of the post is that with Angular we can implement a global error handling implementation where we can catch all our errors across the application and implement some kind of notification/redirect/logging.

This is a great approach, however, if you are using NGRX Effects, we need to tweak this flow. Why is this? Because our effect streams end when a observable error occurs and since NGRX effects are a continuous stream of actions, it breaks the stream.

Let get started with a practical case, lets say you have a HTTP service that makes a request for a specific item, so like: api/pizza/123 and the response from the server is 404 because there is no pizza/123 defined. Typically you want to redirect the user to a 404 page or throw some notification. We can leverage interceptors to handle this interaction essentially treating the interceptor like a side effect. That might look something like this:

I mentioned above we are essentially treating this like a side effect, that said you don’t HAVE to have a interceptor to do this, you could implement your own custom action/effect for errors and handle it that way.

Next, we need to make sure we don’t break the stream when an error occurs. In this situation, we need to implement catchError in our effects and either return an empty observable or some kind of custom action. This looks something like this:

Pretty cool huh? Combining our interceptors with ngrx-effects is really easy and powerful to handle some of these common cases with ease!

I’m #ngPanda

I hope you enjoyed the post, if you liked it follow me on Twitter and Github for more JavaScript tips/opinions/projects/articles/etc!