typescript / intermediate
Snippet
Building Custom Exception Classes with Restored Prototype Chains
When extending built-in classes like Error in TypeScript, compiled ES5 code can break the prototype chain, causing instanceof checks to fail. Calling Object.setPrototypeOf explicitly restores the correct instance linkage.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class ValidationError extends Error {public readonly code: string;constructor(message: string, code: string) {super(message);this.code = code;this.name = 'ValidationError';Object.setPrototypeOf(this, ValidationError.prototype);}}try {throw new ValidationError('Invalid email format', 'ERR_INVALID_EMAIL');} catch (err) {if (err instanceof ValidationError) {console.log(`[${err.code}] ${err.message}`);}}
Breakdown
1
class ValidationError extends Error {
Defines a custom error class inheriting from the standard JavaScript Error class.
2
Object.setPrototypeOf(this, ValidationError.prototype);
Explicitly re-attaches the prototype chain so instanceof checks work across target ES versions.
3
if (err instanceof ValidationError) {
Safely verifies if the caught exception is specifically a ValidationError instance.