javascript / expert
Snippet
Custom Error Classes with Enhanced Stack Trace Customization
In Node.js expert error handling, extending native Error classes requires maintaining proper stack trace frames and chained cause references. Error.captureStackTrace(this, TargetConstructor) omits constructor frames from the stack, keeping context clean for telemetry. The ES2022 cause option preserves root causes across abstraction layers.
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 DomainError extends Error {constructor(message, options = {}) {super(message, options);this.name = this.constructor.name;this.timestamp = Date.now();Error.captureStackTrace(this, this.constructor);}}class ValidationFailedError extends DomainError {constructor(fields, cause) {super('Validation failed for target fields', { cause });this.fields = fields;}}try {throw new TypeError('Invalid string input format');} catch (err) {const domainErr = new ValidationFailedError(['username', 'email'], err);console.log(domainErr.name, domainErr.fields, domainErr.cause.message);}
nodejs
Breakdown
1
class DomainError extends Error {
Defines a custom base domain error inheriting from the native V8 Error object.
2
Error.captureStackTrace(this, this.constructor);
Truncates the V8 stack trace at this constructor call for accurate error callsite reporting.
3
super('Validation failed for target fields', { cause });
Uses ES2022 Error cause chaining to wrap the underlying diagnostic failure.