javascript / expert
Snippet
Structured Domain Exception Hierarchy via Error.captureStackTrace
Custom error classes in production Node.js services require stack trace sanitization and metadata preservation. By inheriting from Error and passing options.cause, we support error chaining introduced in modern Node.js versions. Utilizing V8's Error.captureStackTrace omits internal constructor frames from the trace, ensuring precise context reporting for monitoring systems.
snippet.js
javascript
1
2
3
4
5
6
7
8
class DomainValidationError extends Error {constructor(message, context = {}, cause = null) {super(message, { cause });this.name = this.constructor.name;this.context = Object.freeze({ ...context });Error.captureStackTrace(this, this.constructor);}}
nodejs
Breakdown
1
class DomainValidationError extends Error {
Defines a custom domain exception class deriving from JavaScript's native Error.
2
super(message, { cause });
Invokes super constructor supporting Native Error Cause for upstream stack tracing.
3
Error.captureStackTrace(this, this.constructor);
Uses V8 API to omit the constructor call itself from generated stack trace logs.