Understanding Angular HTTP interceptors

Sneha Agarwal
3 min readOct 22, 2020

Interceptors are a way or a mechanism to intercept outgoing/incoming HTTP requests. By intercept, it means that an interceptor can mutate the value of the request. When the HTTP request is made to the server, a piece of code that we write as an interceptor is triggered just before the completion of the request, meaning this piece of code performs its operation before each request completion.

Common use cases of interceptor:

  1. It allows us to add authentication tokens(e.g. JWT) to the request headers.
  2. Error handling of all the outgoing requests.
  3. Modify or transform response formats.

Let us know more about error interceptors.

Error Interceptor

Proper error handling is essential and very important to make an application robust. Error interceptor is one of the best mechanism that is used for handling the errors that may arise while making HTTP requests. It will automatically handle the errors occurring in multiple services used by our application. If we want to modify our error handling we just need to change one particular file that we call as an error interceptor.

By now we already have got some brief knowledge about interceptors or error interceptor in particular. Let us now see how can we implement them in our Angular code.

http-error.interceptor.ts

import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpResponse,
HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
retry(1),
catchError((error: HttpErrorResponse) => {
let errorMessage = '';
switch (error.status) {
case 401:
errorMessage = `Error Code:${error.status} \nMessage: The user is not authorized`;
console.log(errorMessage);
return throwError(error);
case 403:
errorMessage = `Error Code: {error.status}\nMessage: The JWT is invalid`;
console.log(errorMessage);
return throwError(error);
default: return throwError(error);
}
})

The above code is the error interceptor logic where we have a basic structure for error handling and how we have taken care of two different kinds of errors.

Here we have a class HttpErrorInterceptor which has a method called intercept. This method takes two parameters: request which is of type HttpRequest and next which is of type HttpHandler. The request can be handled by the HttpHandler that is passed to interceptor methods. It returns an Observable of type HttpEvent.

Normally an interceptor mutates the outgoing request before returning next.handle(req). If we simply return next.handle(req), this means we are sending our request to the server without making any change to our request.

An interceptor can similarly perform the mutation over our response as well. Like here, we are performing pipe to the response returned by handle method.

In our scenario, we are checking for errors if any. So if in case our HTTP request fails, then on the basis of the error’s status code, with the help of switch case, we are logging our error message.

app.module.ts

...
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpErrorInterceptor } from './interceptor/http-error.interceptor';
@NgModule({
imports: [
...
HttpClientModule
],
providers: [
...
{ provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true }
],
...
})
...

In app.module.ts file import the HttpErrorInterceptor class and register it in the providers array.

The interceptor file is provided as HTTP_INTERCEPTORS. Multi is kept as true to facilitate the provision for multiple interceptors.

Conclusion:

The above was the basic implementation of angular error interceptor. Similarly we can use interceptors for various other use cases and make our development simpler.

Thank you for reading!!

--

--