...

/

Creating a Global Error Handler

Creating a Global Error Handler

Learn how to create a global error handler for handling server and client-side errors.

The Angular framework provides the ErrorHandler class for handling errors globally in an Angular application. The default implementation of the ErrorHandler class prints error messages in the browser console window. To create a custom error handler for our application, we need to sub-class the ErrorHandler class and provide our tailored implementation for error logging:

  1. Create a file named app-error-handler.ts in the src\app folder of an Angular application.

  2. Add the following import statements:

Press + to interact
import { HttpErrorResponse, HttpStatusCode } from '@angular/common/http';
import { ErrorHandler, Injectable } from '@angular/core';
  1. Create a TypeScript class that implements the ErrorHandler interface:

Press + to interact
@Injectable()
export class AppErrorHandler implements ErrorHandler {}

The AppErrorHandler class must be decorated with the @Injectable() decorator because we will need to provide it later in the main application module.

  1. Implement the handleError method from the ErrorHandler interface as follows:

Press + to interact
handleError(error: any): void {
const err = error.rejection || error;
if (err instanceof HttpErrorResponse) {
switch(err.status) {
case 0:
console.error('Client error:', error.error);
break;
case HttpStatusCode.InternalServerError:
console.error('Server error:', error.error);
break;
case HttpStatusCode.BadRequest:
console.error('Request error:', error.error);
break;
default:
console.error('Unknown error:', error.error);
}
} else {
console.error('Application error:', err)
}
}
  1. In the preceding method, we check if the error object contains a rejection property. Errors that originate from the Zone.js library, which is responsible for the change detection in Angular, encapsulate the actual error inside that property. ...