Photo by Brett Jordan on Unsplash

Angular Error Interceptor

Michael Karén

--

When applications make HTTP requests and fail, we need to handle them. Ideally, we take care of these errors in one place in our code. In this article, we discover how to handle these exceptions in Angular by using an interceptor. We look into the best steps to take directly in the interceptor before sending errors on their way to the error handler.

What are Angular interceptors?

Interceptors are unique Angular services that we can implement to add behavior to HTTP requests in our application. HttpInterceptor provides a way to intercept HTTP requests and responses. In this sense, each interceptor can handle the request entirely by itself.

As the diagram above shows, the interceptors are always in the middle of an HTTP request. As middlemen, they allow us to perform operations on the requests on their way to and back from the server, making it a perfect place to centralize code for things like adding headers, passing tokens, caching, and error handling.

What is an error interceptor?

An error interceptor is a special kind of interceptor used for handling errors that happen when making HTTP requests. Errors come either from the client-side (browser) or the server-side when the request fails for some reason. If the request fails on the server, HttpClient returns an error object instead of a successful response. When an error occurs, you can inform the user by reacting to the error details, or in some cases, you might want to retry the request.

If you are looking into more ways of using interceptors, then this article has plenty of them:

Implementing the interceptor

To create an interceptor, declare a class that implements the intercept() method of the HttpInterceptor interface:

The intercept() method lets us inspect or alter a request. The next object represents the next interceptor in the chain…

--

--

Michael Karén

Frontend Architect • JavaScript Enthusiast • Educative.io Author • ngVikings organizer.