javascript / expert
Snippet
Hierarchical Error Cause Chaining in Next.js Server Components
Leveraging standard JavaScript Error.cause allows expert developers to preserve lower-level upstream error stack traces when re-wrapping domain exceptions in Next.js Server Components, granting granular error boundary telemetry.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export class DatabaseError extends Error {constructor(message: string, cause?: unknown) {super(message, { cause });this.name = 'DatabaseError';}}export async function fetchUserData(userId: string) {try {const res = await fetch(`https://api.internal/users/${userId}`);if (!res.ok) throw new Error(`HTTP status ${res.status}`);return await res.json();} catch (err) {throw new DatabaseError(`Failed fetching user profile for ID ${userId}`, err);}}
nextjs
Breakdown
1
super(message, { cause });
Passes the lower-level caught exception into the native Error constructor via the options object cause property.
2
throw new DatabaseError(`Failed fetching user profile for ID ${userId}`, err);
Wraps the underlying fetch failure in a domain-specific error context while preserving the full cause trace.