paint-brush
Global HTTP request error catching in Angular 2by@luukgruijs
88,438 reads
88,438 reads

Global HTTP request error catching in Angular 2

by Luuk GruijsMay 13th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Whenever you do an <a href="https://hackernoon.com/tagged/http" target="_blank">HTTP</a> 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.
featured image - Global HTTP request error catching in Angular 2
Luuk Gruijs HackerNoon profile picture

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: https://medium.com/@luukgruijs/global-http-error-catching-in-angular-4-3-9e15cc1e0a6b

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 .

Conclusion

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