0 day streak
javascript / intermediate
Snippet

Building Domain-Specific Exception Hierarchies with Custom Error Classes

Inheriting from the built-in Error class allows applications to establish custom error hierarchies. Using instanceof checks inside Angular's GlobalErrorHandler enables type-safe, polymorphic exception handling.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { ErrorHandler, Injectable } from '@angular/core';
export class AppDomainError extends Error {
constructor(public code: number, message: string) {
super(message);
this.name = 'AppDomainError';
Object.setPrototypeOf(this, AppDomainError.prototype);
}
}
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: unknown): void {
if (error instanceof AppDomainError) {
console.error(`Domain Error [Code ${error.code}]: ${error.message}`);
} else {
console.error('Unhandled runtime error:', error);
}
}
}
angular
Breakdown
1
export class AppDomainError extends Error {
Creates a specialized domain error class by inheriting from the standard JavaScript Error superclass.
2
super(message);
Calls the parent Error constructor to properly initialize the message property and capture stack traces.
3
if (error instanceof AppDomainError) {
Uses polymorphic runtime type checking to identify and handle domain-specific exceptions distinctly.