javascript / expert
Snippet
Hierarchical Custom Error Chains with Error Cause Traversal
ES2022 introduced native error chaining using the cause option in the Error constructor. By extending Error into a custom domain class, developers can wrap low-level system or driver failures inside high-level application context while maintaining inspectable error chains that can be recursively traversed to diagnose root causes.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class ApplicationError extends Error {constructor(message, options = {}) {super(message, options);this.name = this.constructor.name;}getRootCause() {let current = this;while (current.cause instanceof Error) {current = current.cause;}return current;}}class DatabaseConnectionError extends ApplicationError {}const rootDbErr = new Error('ECONNREFUSED 127.0.0.1:5432');const dbErr = new DatabaseConnectionError('Failed to query user records', { cause: rootDbErr });console.log(dbErr.getRootCause().message);
nodejs
Breakdown
1
super(message, options);
Invokes the base Error constructor, attaching the native cause property if provided in options.
2
this.name = this.constructor.name;
Dynamically sets the error name to match the derived class constructor identifier.
3
while (current.cause instanceof Error)
Recursively walks down the nested cause property tree to locate the bottom-most error.
4
{ cause: rootDbErr }
Standardized ES2022 property that preserves the original low-level exception inside the higher-level domain error.