javascript / intermediate
Snippet
Custom Global ErrorHandler for Uncaught Exceptions
Angular provides the ErrorHandler class as an extensible hook for catching uncaught exceptions across the application lifecycle. By subclassing ErrorHandler, developers can inspect both synchronous runtime failures and asynchronous errors (such as unhandled HTTP responses). Running notification logic inside NgZone.run ensures UI side effects trigger Angular change detection even when errors originate outside the standard execution context.
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
import { ErrorHandler, Injectable, NgZone, inject } from '@angular/core';import { HttpErrorResponse } from '@angular/common/http';import { NotificationService } from './notification.service';@Injectable()export class GlobalLoggingErrorHandler implements ErrorHandler {private readonly zone = inject(NgZone);private readonly notifier = inject(NotificationService);handleError(error: unknown): void {const timestamp = new Date().toISOString();const errorDetails = error instanceof HttpErrorResponse? `HTTP ${error.status}: ${error.message}`: error instanceof Error ? error.stack ?? error.message : String(error);console.error(`[${timestamp}] Uncaught Error:`, errorDetails);this.zone.run(() => {this.notifier.showToast('An unexpected application error occurred.');});}}
angular
Breakdown
1
export class GlobalLoggingErrorHandler implements ErrorHandler {
Implements the central Angular ErrorHandler interface to override the default console error logging.
2
const errorDetails = error instanceof HttpErrorResponse
Performs type discrimination to extract appropriate details depending on whether the error is network-related or a standard Error.
3
this.zone.run(() => {
Re-enters the Angular execution zone so that UI updates like toast notifications trigger change detection immediately.