javascript / expert
Snippet
Custom Structured Error Hierarchy with Cause Propagation
Leverages ECMAScript native Error cause chaining and object serialization override to construct domain-specific error objects for Next.js error boundary state recovery.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
export class DomainValidationError extends Error {constructor(message, { code = 'ERR_DOMAIN_VALIDATION', cause, metadata = {} } = {}) {super(message, { cause });this.name = this.constructor.name;this.code = code;this.metadata = metadata;this.timestamp = Date.now();}toJSON() {return {error: this.name,code: this.code,message: this.message,metadata: this.metadata,cause: this.cause instanceof Error ? this.cause.message : this.cause,};}}
nextjs
Breakdown
1
super(message, { cause });
Calls the parent Error constructor passing options object containing the original inner error cause.
2
this.name = this.constructor.name;
Dynamically assigns the error instance name property matching the derived constructor class identifier.
3
toJSON() {
Defines custom serialization logic executed automatically when passing error instances to JSON.stringify().