typescript / intermediate
Snippet
Subclassing Error for Custom Exception Hierarchies
Extending the native Error class enables domain-specific error handling with additional metadata like targeted fields while preserving stack traces.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class ValidationError extends Error {constructor(public readonly field: string, message: string) {super(message);this.name = 'ValidationError';}}function parseAge(input: unknown): number {if (typeof input !== 'number') {throw new ValidationError('age', 'Expected age to be a number');}if (input < 0 || input > 120) {throw new ValidationError('age', 'Age must be between 0 and 120');}return input;}
Breakdown
1
class ValidationError extends Error {
Declares a custom error subclass inheriting from the built-in Error class.
2
constructor(public readonly field: string, message: string) {
Automatically initializes and attaches a public readonly field property to the error instance.
3
super(message);
Invokes the parent Error constructor to establish the error message and call stack.
4
throw new ValidationError('age', 'Expected age to be a number');
Instantiates and throws the custom error with domain context.