Global HTTP request error catching in Angular 2 by@luukgruijs
88,345 reads

Global HTTP request error catching in Angular 2

Read on Terminal Reader

Too Long; Didn't Read

featured image - Global HTTP request error catching in Angular 2
Luuk Gruijs HackerNoon profile picture


Luuk Gruijs
react to story with heart


Whenever you do an HTTP request, there are things that could go wrong. If things go wrong the request will return a response with an error code. Based on this error code you for example want to inform the user what went wrong.

Looking for an Angular 4.3+ solution? Read this instead:

You can only deal with errors if you attach a catch to your request. This can possibly look like this:

When your application grows, the amount of HTTP requests increases as well. Attaching a catch to every request is not exactly DRY. We can fix this by extending the HTTP class from Angular and attach a catch to the request method.

Creating the HTTPInterceptor class

You might already have such a class in your Angular project as we can use such a class as well to for example attach specific headers to each request. If you don’t have one yet, let’s create one now:

In this class we overwrite the request method with our own implementation. Our implementation attaches a catch to each request and exposes a handleError method. Every response that ends up in the catch will be passed into this method. This method has to return an Observable in order to work.

Now it’s important to make every request use our HttpInterceptor class instead of the default Http class. Lucky for us, this is quite easy:

As you can see we updated our constructor. http is now of class HttpInceptor . We also removed the catch in our request, as that is now handled by the HttpInterceptor .


Using the HttpInterceptor class we can easily attach a catch to all requests and make sure that potential errors are taken care of properly.

Thanks for reading. Any feedback? Let me know.

Follow me on Medium and let’s connect on LinkedIn


. . . comments & more!
Hackernoon hq - po box 2206, edwards, colorado 81632, usa