javascript / intermediate
Snippet
Global Error Handling with ErrorHandler
Providing a custom ErrorHandler allows you to centralize logging and exception tracking across your entire application instead of handling errors in every component.
snippet.js
1
2
3
4
5
6
7
8
9
import { ErrorHandler, Injectable } from '@angular/core';@Injectable()export class GlobalErrorHandler implements ErrorHandler {handleError(error: any): void {const message = error.message ? error.message : error.toString();console.error('Captured Global Error:', message);}}
angular
Breakdown
1
export class GlobalErrorHandler implements ErrorHandler {
Implements the standard interface to override default error behavior.
2
handleError(error: any): void {
The required method called by Angular whenever an uncaught exception occurs.
3
console.error('Captured Global Error:', message);
Logic to process the error, which could include sending it to a server.