Skip to main content

Angular 7: Intercepting HTTP call to handle API errors.

Error handling is one of the most cruicial but neglected item of frontend development. There are number of errors that can happen on frontend and they are of different types. Following are different types of errors that our users can encounter


  1. Javascript errors e.g when you divide a number by a dynamic input and the input is 0
  2. Errors in calling server APIs.
I want to discuss the server errors in this article. When we call an API there can be several problems, for example on a login authentication form when you call your server API to authenticate user, you can have following possibilities

  1. The device has lost internet connection
  2. The code on server is not working properly
  3. You have made a typo in the API end point name
  4. The user account is not valid and server returns an error code or an error status
All these scenarios must be handled and gracefully inform the user about the error with a suggestion to recover from the error state. Obviously you cannot write code in all API calls to handle all error conditions. Surely you don't have to do this. In Angular you can write HTTPInterceptor to handle these conditions at one location in your code and for special cases where a component wants to handle on it own you can pass the error on and component and provide its own implementation too.

Following are the steps to implement the error handler.

Step 1:
Write a class that extends HttpInterceptor interface from Angular common http library.

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

@Injectable()
export class MyInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {
    return next.handle(req);
  }
}
Step 2:

Add error handling logic your interceptor.

intercept (
  request: HttpRequest<any>,
  next: HttpHandler
): Observable<HttpEvent<any>> {
  return next.handle(request)
    .pipe(
      retry(1),
      catchError( (error: HttpErrorResponse) => {
        if (error.error instanceof ErrorEvent) {
          console.log('Client side error'); 
        } else {
          this.messageService.add(error.message);
        }
        return throwError(error);
      })
    );
}
In the above code snippet the MessageService was injected in the interceptor using the constructor as we do in all other Angular components.

Step 3:
Write MessageService to display an elegant error message in front of user. For simplicity I am passing the actual API error message here to the message service, you can refine this implementation and provide better error messages based on the error status.


Step 4:
Make your angular engine aware about your newly created interceptor. Import it in your module file and add it in your providers list like the following

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyInterceptor } from './my-interceptor';
...
providers: [
  { provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true },
]
...
That's all you have to do to handle errors in Angular2 application.


Comments

Popular posts from this blog

Html5 Canvas Drawing -- Draw dotted or dashed line

This post is for those who want to use html5 canvas for drawing. The canvas API now has built in methods to create lines with dashes. The method is called setLineDash. Following is the code sample to create dashed line. var canvas = document . getElementById ( "canvas" ); var ctx = canvas . getContext ( "2d" ); ctx . setLineDash ([ 5 , 3 ]); /*Dash width and spaces between dashes.*/ ctx . beginPath (); ctx . moveTo ( 0 , 100 ); ctx . lineTo ( 400 , 100 ); ctx . stroke (); If you want to draw lines having a custom style there is no methos in the API. But fortunately there is a way to achieve this. Following is a description about how I achieved this. You can set the stroke pattern on canvas context. Stroke pattern can be created using any image. You create image for your custom pattern and set strokeStyle of the context like the following: var linePattern; imageToUsedAsPattern.onload = function() { linePattern = context.createPattern(imageToU...

Difference between ng-template, ng-content and ng-container

While working on a very complex feature for a client in which I had to present hierarchical dynamic data in three column layout with ability to expand like google image search on each level, I came across ng-content, which seemed like a perfect fit for the solution I was thinking about implementing. But I got confused between ng-content and ng-container when I saw the generated html while debugging my code in developer console. I further investigated both ng-content and ng-container and decided to write my finding here in my blog for future references. If you are also wondering what are they for, read on. <ng-container> When you have to write different host elements to combine many structural component like the following <div *ngIf="condition"> <div *ngFor="..."> Some content here </div> </div> You get many unintentional host elements which are not required for your layout. It becomes a prolem when you have complex appl...

Angular 2+: ng-content

Have you ever felt the need of writing a component like the following <my-component> <div> Some text here </div> <div> Some text here </div> <div> Some text here </div> <div> Some text here </div> </my-component> Now your intention here is to have your custom component and keep having the additional html that you have written between statring and ending tags. If yes, then you are on the right place. Angular provides an element called ng-content which can used to write configurable components. This is called Component Projection, neaning the content that will be procvided inside the opening and closing brackets will be projected. It will be rendered inside a <ng-content> element. It means that you must include a <ng-content> tag somewhere in your components html template so that the provided content can be projected inside it. So your my-component should have a template like the following // myCompo...