Angular 5 Global HTTP Error Interceptor!

0
8584
views

Angular 5 Global HTTP Error Interceptor: At some point in your application you feel the need like handling the HTTP errors, Whenever you do an HTTP request or make an API there are chances that things might go wrong. HTTP error interceptor in Angular tracks down each and every API call you make to the server from the Front End. This HTTP error interceptor will return a response with an error code. Based on the error status code you can tell the user what exactly is happening whether he is unauthorised or internet connection failure happened as such.

Anyway whenever you make an API call to the server, server will return you the response but when server won’t send its response handling errors such as 502, 401, internet connection failures makes it all the more difficult.

It would be more handy that if you implement this HTTP error interceptor globally so that you don’t have to repeat same code in all other components. A new HttpModule was introduced in Angular 4+ that allows us to make use of interceptor globally.

Angular 5 Global HTTP Error Interceptor

The idea here is that whenever you make an API call to the server. Each and every request was routed through this interceptor, this will even allow you to add and remove certain properties to each request.

Since every API call you are making goes through this interceptor, we can also use this interceptor to catch all the requests that return as an instance of HttpErrorResponse.

This looks something like this:
Create an http_error_interceptor.ts file in your project put this below mentioned code.

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse,
  HttpErrorResponse,
} from '@angular/common/http';
 
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
 
import { ErrorHandler } from './error_handler';
 
@Injectable()
export class RequestInterceptor implements HttpInterceptor {
 
  constructor(
    public errorHandler : ErrorHandler,
  ) {}
 
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).do((event: HttpEvent<any>) => {}, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        this.errorHandler.handleError(err);
      }
    });
  }
}

As you can see in the code we send the request to the HttpHandler and then execute the request. In the callback function we check for errors. If the error is an instance of HttpErrorResponse we can send the request to an error handler that displays a nice little message with what went wrong.

Let’s implement http error handler so that we can display some nice error messages.

Angular 5 Global HTTP Error Interceptor

Create an error_handler.ts file in your project put this below mentioned code.

import { Injectable } from '@angular/core';
import { MatSnackBar } from '@angular/material';
import { LoginService } from './login.service';

@Injectable()
export class ErrorHandler {
  public onlineFlag =navigator.onLine;

  constructor(
    public snackbar: MatSnackBar,
    public login:LoginService
  ) {}

  public handleError(err: any) {
    this.snackbar.open(err.message, 'close');
    console.log(err.message);
    if(err.status==401){
        window.localStorage.clear();
        this.login.informLogout('sss');
    }
    else if(!this.onlineFlag){
      //console.log("Internet connected");
      alert("Internet connection lost");
      // alert(this.onlineFlag);
       window.localStorage.clear();
       this.login.informLogout('sss');
    }
  }
}

As you can see in the code I am tracking for 401 if the user is unauthorised I am immediately logging him/her out. I am also checking here for internet connection failure using navigator.onLine if it returns false then internet is not connected. If it is true we are good with internet connection.

Don’t Forget
Don’t forget to mention the below code in the provider section of app.module.ts file

 providers: [LoginService, DataService, AuthService, RoleGuardService, ErrorHandler,
    DataService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true,
    },],

This HTTP error interceptor was very useful when your application is full of API calls you needed something globally to handle errors and display some nice error messages.

I hope this was helpful, Thanks for reading
Happy Coding!