javascript / intermediate
Snippet
Capturing Unhandled Application Exceptions with a Custom Global ErrorHandler
Angular provides a central ErrorHandler hook that receives all unhandled exceptions thrown across templates, services, and lifecycle hooks. By implementing the ErrorHandler class and branching control flow based on runtime error types (such as distinguishing network errors from runtime JavaScript Error objects), you can extract meaningful diagnostics and forward them to external monitoring tools.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { ErrorHandler, Injectable, inject } from '@angular/core';import { HttpErrorResponse } from '@angular/common/http';import { LoggingService } from './logging.service';@Injectable()export class GlobalApplicationErrorHandler implements ErrorHandler {private readonly logger = inject(LoggingService);public handleError(error: unknown): void {if (error instanceof HttpErrorResponse) {this.logger.logHttpFailure(`Status: ${error.status} - ${error.message}`);return;}if (error instanceof Error) {this.logger.logFatalCrash({name: error.name,message: error.message,stack: error.stack ?? 'No stack trace available'});return;}this.logger.logUnknown(String(error));}}
angular
Breakdown
1
export class GlobalApplicationErrorHandler implements ErrorHandler {
Declares a class adhering to Angular's ErrorHandler interface to override default error handling behaviour.
2
public handleError(error: unknown): void {
Defines the required entrypoint method invoked by the Angular framework whenever an uncaught exception occurs.
3
if (error instanceof HttpErrorResponse) {
Uses type narrowing to inspect whether the incoming error originated from an unhandled HTTP request.
4
if (error instanceof Error) {
Branches execution for standard JavaScript Error instances to safely access message and stack properties.