javascript / expert
Snippet
Custom Error Hierarchy with Cause Chains in Next.js Server Actions
Creating domain-specific Error subclasses with ECMAScript cause chaining allows Next.js Server Actions to securely capture upstream technical exceptions while normalizing user-facing payloads.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export class ActionError extends Error {constructor(message, status = 500, cause = null) {super(message, { cause });this.name = 'ActionError';this.status = status;this.timestamp = Date.now();}}export function handleActionFailure(err) {if (err instanceof ActionError) {return { success: false, error: err.message, status: err.status, rootCause: err.cause?.message };}return { success: false, error: 'Internal Server Error', status: 500 };}
nextjs
Breakdown
1
super(message, { cause });
Passes the original exception context to the standard Error constructor via the cause property option.
2
if (err instanceof ActionError) {
Uses prototype checking to distinguish expected domain errors from unexpected internal server failures.
3
rootCause: err.cause?.message
Safely retrieves nested error message metadata using optional chaining.