In this tutorial, we are going to demonstrate how to handle errors properly in our Angular applications.

Error handling in software development is as important having a working application. In order to have a complete and robust application, errors and exceptions have to be properly handled. Handling errors is a way of telling your users “hey dude! Calm down, here is the problem and here is the way out”, assurance, yeah? :).

In this tutorial, I will walk you through how to efficiently handle errors in your Angular Application. I will be using latest version of  Angular 7.0.4 for this tutorial and I will advise you use the same.

Prerequisites

For the purpose of this tutorial the following has to be available on your system;

  1. Install Node
  • Go to nodejs
  • Download and install the available LTS version.
  • To check your version, run node -v in a terminal/console window.
  1. Install Angular CLI
     npm i -g @angular/cli 
    
  2. Visual Studio Code. I use VSCode but you can choose to use any other IDE (Angular IDE, Atom, Vim etc.)

With all these prerequisites in place, we can start by creating a new folder for our application.

      • Open the folder in VSCode by right clicking in the folder and open with VSCode.
      • Open VsCode terminal and create a new angular project
              ng new my-ErrorHandling-app 
         
        
      • The ng newcommand prompts you for information about features to include in the initial app project. Accept the defaults by pressing the Enter or Return key.
      • Cd into the project folder cd myErrorHandlingApp
      • Serve the application locally.
              ng serve -o 
        

This will open the application in your local browser on localhost:4200, you should see this Angular

Error in Angular application can either be a Client-Side error or Server-Side error;

  • Client-side error: These are errors related to Front-end code and the Network, they throw 4xx status codes.
  • Server-side error: These are errors related to Back-end codes, database and file system. They usually throw 5xx status codes.

For the purpose of this tutorial, we are going to demo error handling by consuming chucknorris API to display random jokes using Angular’s in-built HttpClientModule.

We start by importing HttpClientModule to our root module (app.module.ts).

       import { BrowserModule } from '@angular/platform-browser';
       import { NgModule } from '@angular/core';
       import { HttpClientModule } from '@angular/common/http';
       import { AppRoutingModule } from './app-routing.module';
       import { AppComponent } from './app.component';

      @NgModule({
        declarations: [
          AppComponent
       ],
       imports: [
          BrowserModule,
          HttpClientModule,
          AppRoutingModule
      ],
       providers: [],
       bootstrap: [AppComponent]
      })
      export class AppModule { }

In app.component.html, we create a button which will initiate an http request on click.

button

In app.component.ts, we include our constructor function and extend the component’s class to implement OnInit lifecycle hook.

 

       
  import {Component, OnInit} from '@angular/core';

  @Component ({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
  })
  export class AppComponent implements OnInit {
    title = 'my-app';
constructor () {}

  makeApiCall () {  
  }

  ngOnInit () {}
   }

Now we need to create a service where we will make our http request. Service is a very important component of Angular. When we need to have some codes to be used everywhere in the application or we need to pass data across the application, services will come in handy.

ng g service appService

This will create a new Injectable service that can be injected into all our components. We should have this on our folder tree now.

After creating the service, we will inject the service into app component controller (app. component.ts file). Notice how the appService is imported into the component.

       
  import {Component, OnInit} from '@angular/core';
  import {AppServiceService } from './app-service.service';
  @Component ({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.scss']
  })
  export class AppComponent implements OnInit {
    title = 'errorHandling-app';
    constructor (appService: AppServiceService) {
          }
    ngOnInit() {}
}

In the appService, we will make our http request to chuck Norris open API to get random jokes.

       
    import { Injectable } from '@angular/core';
  import { HttpClient } from '@angular/common/http';

  @Injectable ({
    providedIn: 'root'
  })
  export class AppServiceService {
  base_Url = 'https://api.chucknorris.io/jokes';

  constructor (private  http: HttpClient) { }

  getJokes (): Observable {
    return this.http.get(`${ this.base_Url }/random`)
  }

  extractJokes () {
    this.getJokes ().subscribe(res => {
      console.log(res);
      })
    }
  }

So, what have I done?

  • I set the base URL for our API to ‘https://api.chucknorris.io/jokes’
  • I injected HttpClient service as a private variable in the constructor function. N.B. You need to import HttpClientModule into app.module.ts from ‘@angular/common/http.
  • I created a getJokes that invokes the http get method to fetch random jokes. This is returned as Observables.
  • In the extractJokes method, I subscribe to the jokes Observable and logging it on the console.

 

Well, I think the next thing we need to do is to call the extractJokes method from controller on click of the button. In the makeApi method, insert this;


      makeApiCall() {
         this.appService.extractJokes();
       }

Now, save your code and click on the button, you should see a joke object on your browser’s console.

Error handling in Angular

Works fine right? :)

We are done with the application and ready to ship. Oh wait!!! What happens if there is any error from our http request, how do we let the user know of the error, how do we handle that.

Now there are many ways of doing this, in the next chapter of this tutorial, let’s explore some of them.

prevChapter 1 of 2