javascript / intermediate
Snippet
Global Application Error Interception with Angular ErrorHandler
Angular provides the ErrorHandler class as a hook for centralized exception handling across the entire application. By extending or implementing ErrorHandler and providing it via dependency injection, uncaught errors occurring inside components, services, or templates can be intercepted, formatted, and sent to remote logging services before gracefully informing the user.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { ErrorHandler, Injectable, Injector } from '@angular/core';import { LoggingService } from './logging.service';@Injectable()export class GlobalLoggingErrorHandler implements ErrorHandler {constructor(private injector: Injector) {}handleError(error: unknown): void {const logger = this.injector.get(LoggingService);const message = error instanceof Error ? error.message : 'Unknown runtime error';const stack = error instanceof Error ? error.stack : '';logger.logError({ message, stack, timestamp: Date.now() });console.error('Captured by GlobalLoggingErrorHandler:', error);}}
angular
Breakdown
1
export class GlobalLoggingErrorHandler implements ErrorHandler {
Defines a custom class implementing Angular's built-in ErrorHandler interface.
2
constructor(private injector: Injector) {}
Injects the Injector to lazily retrieve dependencies like logging services, avoiding circular dependency issues during early application bootstrap.
3
handleError(error: unknown): void {
Overrides the core callback method triggered whenever an uncaught exception bubbles up in the Angular zone.
4
const message = error instanceof Error ? error.message : 'Unknown runtime error';
Performs type narrowing on the unknown error object to safely extract standard JavaScript error properties.