Photo by Brett Jordan on Unsplash

Angular Error Interceptor

Michael Karén
3 min readJan 31, 2022

--

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…

--

--

Michael Karén

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