Creating a Global Error Handler
Learn how to create a global error handler for handling server and client-side errors.
We'll cover the following...
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:
Create a file named
app-error-handler.tsin thesrc\appfolder of an Angular application.Add the following
importstatements:
Create a TypeScript class that implements the
ErrorHandlerinterface:
The AppErrorHandler class must be decorated with the @Injectable() decorator because we will need to provide it later in the main application module.
Implement the
handleErrormethod from theErrorHandlerinterface as follows:
In the preceding method, we check if the
errorobject contains arejectionproperty. Errors that originate from the Zone.js library, which is responsible for the change detection in Angular, encapsulate the actual error inside that property.After extracting the error in the
err...