Skip to main content
angular-8-HTTP-error-interceptor

Create Common Http Error Interceptor into Angular8

This angular 8 tutorial help to create a common HTTP API handler for angular 8 application. The HttpInterceptor is used to handle client-side errors gracefully and display them to the user. It helps to create a custom interceptor to catch all error responses from the server in a single location.

We’ll create a helper common file error.http-api.ts file that would be located in the /src/app/_helpers/ folder. This file intercepts HTTP responses from the API to check if there were any errors.

You can create custom rule based API response like logout if the token expired or received 401 HTTP response, Rest of all other errors are thrown up to the calling service , So that alert can be displayed to the user at the client side.

We will use inbuilt HttpInterceptor class that was introduced in Angular 4.3.

Common Exception Handler method

Let’s create HTTP API handler in angular 8 application. We will extend HttpInterceptor class and implement our custom Error handle and throw meaningful information to the end user.

Http interceptors are added to the request pipeline in the providers section of the app.module.ts file.

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

import { AuthService } from '@/_services';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor(private authService: AuthService) {}

    intercept(request: HttpRequest, next: HttpHandler): Observable<httpevent> {
        return next.handle(request).pipe(catchError(err => {
            if (err instanceof HttpErrorResponse) {
			   if(err.status === 401) {
					// auto logout if 401 response returned from api
					this.authService.logout();
					location.reload(true);
				} else {
					const error = err.error.message || err.statusText;
					return throwError(error);
				}
            }
        })
		.finally(() => {
        console.log('finally');
      });
	)}
}

As you can see into the above code, We will send the request to the HttpHandler and execute the request. There is callback method that responsible to check for errors. If the error is an instance of HttpErrorResponse and http status code is 401, We will redirect to login page.

Let’s add HTTP_INTERCEPTORS into the provider section of app.module.ts file

providers: [LoginService, DataService, AuthService, RoleGuardService, ErrorHandler,
   DataService,
   {
     provide: HTTP_INTERCEPTORS,
     useClass: ErrorInterceptor,
     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 you guys have enjoyed to read article, Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *