javascript / intermediate
Snippet
Custom Global ErrorHandler Implementation for Runtime Exception Logging
Angular provides the ErrorHandler class to capture uncaught exceptions globally throughout the application lifecycle. By creating an Injectable class that implements ErrorHandler, developers can customize error normalization and delegate error messages to external loggers without crashing the runtime.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import { ErrorHandler, Injectable } from '@angular/core';@Injectable()export class GlobalLoggingErrorHandler implements ErrorHandler {handleError(error: unknown): void {const message = error instanceof Error ? error.message : String(error);const stack = error instanceof Error ? error.stack : 'No stack trace';console.error(`[Application Error]: ${message}`, { stack });}}
angular
Breakdown
1
export class GlobalLoggingErrorHandler implements ErrorHandler {
Defines a custom service adhering to Angular's ErrorHandler interface contract.
2
handleError(error: unknown): void {
Receives the raw uncaught error payload passed by the framework.
3
const message = error instanceof Error ? error.message : String(error);
Safely checks the type of the incoming error to extract a readable message string.
4
console.error(`[Application Error]: ${message}`, { stack });
Logs the structured error message along with the optional stack trace.