javascript / expert
Snippet
Structured Error Propagation with Custom Stack Sanitization
Node.js allows custom stack trace trimming via Error.captureStackTrace to omit internal constructor logic from error dumps. Combined with native cause chaining and context metadata, this enables precision error handling and domain-specific branching.
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
23
24
25
26
class DomainControlError extends Error {constructor(message, contextData, causeError) {super(message, { cause: causeError });this.name = this.constructor.name;this.context = contextData;if (Error.captureStackTrace) {Error.captureStackTrace(this, DomainControlError);}}}function processWorkflow(payload) {try {if (!payload.id) throw new TypeError('Missing payload identifier');} catch (err) {throw new DomainControlError('Workflow execution halted', { step: 'VALIDATION' }, err);}}try {processWorkflow({});} catch (err) {if (err instanceof DomainControlError && err.context.step === 'VALIDATION') {console.error(`Handled: ${err.message}, Root Cause: ${err.cause.message}`);}}
nodejs
Breakdown
1
super(message, { cause: causeError });
Chains the underlying error using ECMAScript native cause context.
2
Error.captureStackTrace(this, DomainControlError);
Strips constructor call details from stack trace in V8 runtime engines.
3
if (err instanceof DomainControlError && err.context.step === 'VALIDATION') {
Performs domain-specific control flow branching based on error context metadata.