JWT Authentication in Angular – Part 2 – Error handling

In the previous part, we created a mechanism for fetching, saving, and adding tokens to headers of HTTP requests. These tokens usually have some expiration time. API receives and validates them. When the token is not valid anymore, API returns an error, which is handled in the front-end app.

How to handle expired tokens?

To be prepared for this scenario, we need to clear the current user state when the token is not valid anymore. To achieve it, we have to create an additional interceptor that catches errors and invokes a logout action in case of a 401 error (Unauthorized). Below, you can see an example of a class that covers expected behavior.

export class ErrorInterceptor implements HttpInterceptor {
  constructor(private authenticationService: AuthenticationService) {}
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((e) => {
        if (e.status === 401) {
const error = e.error?.message || e.statusText;
return throwError(() => new Error(error));

To make it work, it should be added to the main module of the application. Finally, we must ensure the providers section contains both JwtInterceptor and ErrorInteceptor.

  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
    { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },

HTTP interceptors are quite a powerful utility of the Angular framework. Using them, we can easily set up the JWT authentication mechanism, which is lightweight and easy to maintain. The ErrorInteceptor discussed in this blog can be used to build an error handling system that covers every error type that returns from API.

Tags: , ,