a blog for those who code

Friday 27 December 2019

Using HTTP Interceptors for Error Handling in Angular


Error handling is one of the key features or concepts of any complete or robust application, which means that all the errors and exceptions should be gracefully handled in our application. In my opinion, it's better to let your users know about the error too like "There is a problem, please try again later". The most efficient place for handling the error is at HTTP Interceptors.

HTTP Interceptors is an interface part of the HttpClient module which is used to intercept or mutate HTTP requests and responses. We can get the access to request headers and body before it is sent to the backend and similarly we can get the response object before using it in the application.

Knowing About HttpClient and How to use it in Angular

Creating HTTP Interceptor is easy, where we just need to create an injectable service and implement an HttpInterceptor Interface like below :

export class ErrorHandlingInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): 
     Observable<HttpEvent> {
       console.log("Error Handling");
       return next.handle(req);
     }
}

Custom Pipes For Everyday Use in Angular

Also, we need to modify the App Module to include our Interceptor in the provider's array as shown below :

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptor } from './MyInterceptor'

providers: [
  {
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorHandlingInterceptor,
    multi: true
  }
]

Now we need to add our Error Handling code in our interceptor which will be as shown below:

import { retry, catchError } from 'rxjs/operators'

export class ErrorHandlingInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent> {
      return next.handle(req)
      .pipe(
        retry(2),
        catchError((err : HttpErrorResponse) => {
          const errorMessage = `Error Code: ${err.status}
                                \nMessage: ${err.message}`;
          return throwError(errorMessage);
        })
      )
    }
}

In the above code, we are first retrying the HTTP request 2 times to make sure that error happens again and then we are using catchError to throw the error to the user. Using HttpInterceptor allows us to have a proper separation of concerns, for example, if we want to change how the error message looks like we can change it in our interceptor class without worrying about anything.

Career Category (English)728x90

No comments:

Post a Comment