NashTech Insights

Error Handling in Angular Application

Alka Vats
Alka Vats
Table of Contents
error

In this blog, we look at how error handling in Angular. We also learn how to create a Global Error handler or custom error handler in Angular. We know why we need to make errors and some of the best practices. In the end, we will learn a few tips like how to Inject services to a global error handler, etc.
If you want to learn about a new feature of angular, you can refer here.

Why Handle Errors?

Handling error is an important part of the application design. JavaScript can throw errors each time something goes wrong. For Example, the Javascript throws errors in the following conditions

  1. When we reference a non-existent variable
  2. The value provided is not in the range of allowed values.
  3. When Interpreting syntactically invalid code
  4. When a value is not of the expected type
  5. Internal errors in the JavaScript engine

Apart from the above, unexpected errors can happen at any time. like broken connection, null pointer exception, no internet, HTTP errors like the unauthorized user, session expired, etc.

Angular handles the errors, but it won’t do anything except write it in the console. And that is not useful either to the user or to the developer.

There are two types of error-handling mechanisms in Angular. One catches all the client-side errors and the other one catches the HTTP Errors.

HTTP Errors

The HTTP Errors are thrown when you send an HTTP Request using the HttpClient Module. The errors again fall into two categories. One is generated by the server like the unauthorized user, session expired, Server down, etc. The Other one is generated at the client side while trying to generate the HTTP Request. These errors could be a network errors, errors while generating the request, etc

The HTTP errors are handled by the HTTP Interceptors

Client Side Errors

All other errors thrown by the code fall into this category. These are handled by the ErrorHandler class, which is the default error handler for Angular.

Default Error Handling in Angular

The default Error handling in Angular is handled by Errorhandler class, which is part of the @angular/core module. This is a global error handler class that catches all exceptions occurring in the App. This class has a method handleError(error). Whenever the app throws an unhandled exception anywhere in the application angular intercepts that exception. It then invokes the method handleError(error) which writes the error messages to the browser console.

Error Handling Example

Create a new Angular application. Add the following code snippet to app.component.html & app.component.ts

app.component.html

<h1> {{title}} </h1>
 
<button (click)="throwError1()"> Throw Error-1 </button>
<button (click)="throwError2()"> Throw Error-2 </button>
 
<router-outlet></router-outlet>

app.component.ts

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent
{
    title: string = 'Global Error Handler in Angular' ;
 
    throwError1() {
      var a= b;  
    }
 
    throwError2() {
      try {
        var a= b;  
      } catch (error) {
         //here you can handle the error
         //
      }
    }
}

The code mimics an error by using the statement,var a= b;, where b is not defined. The first method throwError1() does not handle errors, while throwError2() method uses try..catch block to handle the error.

Run the app and keep the Chrome developer tool open. Click on the throw error 1 button. The default Error Handler of angular intercepts the error and writes to the console as shown in the image below

But, clicking on the throw error 2 button does not trigger the Error Handler as it is handled by using the try..catch block.

If you are not handling the error in the try..catch block, then you must use throw error it so that the default error handler can catch it.

    throwError2() {
      try {
        var a= b;  
      } catch (error) {
        throw error;    //rethrow the error
      }
    }

Global Error Handler

The built-in ErrorHandler is a simple solution and provides a good option while developing the app. But it does not help to find out the error thrown in the production environment. We have no way of knowing about the errors which happen at the user’s end.

Hence, it is advisable to create our own global error handler class, because

  1. We can show a simple error page to the user, with a option to retry the operation
  2. We can log the errors back to the back-end server, where we can read all the errors. Then we can make the necessary changes to the app to remove the error
How to Create a Global Error Handler?

To create a custom error handler service, we need to use the following steps.

First, create a GlobalErrorHandlerService  which implements the ErrorHandler
Then, override the handleError(error) method and handle the error.

export class GlobalErrorHandlerService implements ErrorHandler {
 
  constructor() { 
  }
 
  handleError(error) {
     console.error('An error occurred:', error.message);
  }
  
}

Next, register the GlobalErrorHandlerService in the Application root module using the token ErrorHandler.

@NgModule({
  ------
  providers: [
    { provide: ErrorHandler, useClass: GlobalErrorHandlerService },
  ]
})
export class AppModule { } 

Best Practices in Handling Errors

Now, we learned how to handle errors, here are a few things you should keep in mind while designing an Error Handler service.

  1. Use a try.. catch block to handle the known errors. Handle it accordingly. If you are not able to handle it, then re-throw it.
  2. Use a global error handler to trap all unhandled errors and notify the user.
  3. The ErrorHandler does not trap HTTP Errors, You need to use HTTP Interceptors to handle HTTP Errors.
  4. Check for the type of error in the error handler and act accordingly.
    • For Example, if is an error from the back end (HTTP Error) you can use the HTTP Status Code to take necessary action.
    • 401 Unauthorized error you can redirect the user to the login page.
    • 500 Internal Server Error you can ask the user to retry after some time while sending a notification to the server administrator e
  5. For all other unhandled errors, log the errors back to the backend server ( or to any third-party error providers). You can then look at those logs and make necessary changes to the app.

Tips for Error Handler

Injecting other services to the global error handler

Angular creates the error handler service before the providers. Otherwise, it won’t be able to catch errors that occur very early in the application. It also means that the angular providers won’t be available to the ErrorHandler.

What if we wanted to use another service in the error handler. Then, we need to use the Injector instance to directly to inject the dependency and not depend on the Dependency injection framework

To do that first, we need to import the injector

Then we need to inject the injector to the GlobalErrorHandlerService.

Finally, use the injector to get the instance of any required service.

The following example service uses the injector to get the Router Service.

import { ErrorHandler, Injectable, Injector} from '@angular/core';
import { Router } from '@angular/router';
 
@Injectable()
export class GlobalErrorHandlerService implements ErrorHandler {
 
    constructor(private injector: Injector) {
    }
 
    handleError(error) {
 
        let router = this.injector.get(Router);
        console.log('URL: ' + router.url);
        console.error('An error occurred:', error.message);
       
       alert(error);
   }
}
 

Conclusion

So let’s conclude now with this blog, we have learned how to create a Global Error handler or custom error handler in Angular. Now, we know why we need to make errors and some of the best practices with also a few tips like how to Inject services to a global error handler. I hope this helps you to understand error handling in angular applications.
Happy reading!!

Finally, for more such posts, please follow our LinkedIn page- FrontEnd Competency.

Alka Vats

Alka Vats

Alka Vats is a Software Consultant at Nashtech. She is passionate about web development. She is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. She is a quick learner & curious to learn new technologies. Her hobbies include reading books, watching movies, and traveling.
%d bloggers like this: