0 day streak
javascript / intermediate
Snippet

Structured Error Chaining with Custom Exception Classes

Custom Error classes extending the standard `Error` class help categorize application failures. Passing an options object with a `cause` property to `super()` creates an explicit error chain for easier debugging.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class DatabaseError extends Error {
constructor(message, cause) {
super(message, { cause });
this.name = 'DatabaseError';
this.code = 'ERR_DB_QUERY_FAILED';
}
}
function fetchUserRecord(userId) {
try {
throw new TypeError('Invalid connection pointer');
} catch (rawErr) {
throw new DatabaseError(`Could not load record for user ${userId}`, rawErr);
}
}
try {
fetchUserRecord(42);
} catch (err) {
console.error(`${err.name}: ${err.message}`);
console.error(`Root cause: ${err.cause.message}`);
}
nodejs
Breakdown
1
class DatabaseError extends Error {
Defines a domain-specific custom exception inheriting standard Error prototype features.
2
super(message, { cause });
Calls the parent Error constructor, registering the original lower-level error under the `.cause` property.
3
console.error(`Root cause: ${err.cause.message}`);
Accesses the chained underlying cause of the custom exception.