Catch and handle all 404 errors from your webservice in Angular 5 or above

Antoine
2 min readApr 29, 2018

I am currently building a website using Angular where I need to catch all the 404 errors returned by my webservice and redirect them to a /not-found page on the front-end, but still be able to handle the other errors separately, directly in my controllers.

Find more articles about programming on my personal blog, including a series of articles for beginner programmers!

The goal is to add this behavior, without touching any of the code in our existing components, as we don’t want to have to modify potentially dozens of components.

Of course, this system is not specific to 404 errors, and you can handle any HTTP error code using the same solution.

Let’s say that we have a component getting BlogPostobjects from the webservice by calling the GET /blogpost/{id} route. Our component has a BlogPostService that sends queries to the webservice, and a BlogPostShowComponent controller that uses this service to get the data and link it to the view, or display an error message if the webservice encounters an error.

Our BlogPost service, simply returning an Observable to the controller
Our BlogPost controller, calling the service and handling the response

We want to keep the current behavior of the controller handling most of the errors on the Observable returned by the service (lines 11 to 13), but we want to redirect the user to the /not-found` page if the webservice returns a 404 error code (i.e. there is no BlogPost with the ID that we use to call the route).

The solution is to take advantage of the possibilities offered by the new HttpClient interface introduced in Angular 5 in replacement of the previous Http interface used to make HTTP requests.

One of the new features is the possibility to use HttpInterceptors that will catch any request made to a webservice, or any response received from a webservice.

The interceptor I use to catch the 404 errors from my webservice

This interceptor will catch any error encountered by a HttpClient anywhere in your application. I then add some condition to filter 404 errors, and, after redirecting the user to the /not-found page, returns an empty Observable so that the error handling in the BlogPostShowComponent is not also triggered.

In case the error is not a 404, it will just throw again the error, that can then be handled in our usual error handling in the controller.

After the class, we define a HttpErrorInterceptorProvider that will allow us to register the interceptor in the application.

The only thing left to do it to actually add the HttpErrorInterceptorProvider in the providers array of our AppModule.

Find more articles about programming on my personal blog, including a series of articles for beginner programmers!

--

--

Antoine

I am a professional software development engineer working for Amazon andI write about programming. Checkout my blog www.mindflash.org — Opinions are my own