javascript / expert
Snippet
Recursive Error Chaining with the 'cause' Property
The 'cause' property in the Error constructor allows for structured error wrapping. This preserves the original error context while providing a high-level message, which is essential for debugging complex service architectures in Node.js.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
async function fetchData() {try {await db.query('SELECT...');} catch (dbErr) {throw new Error('Failed to retrieve user data', { cause: dbErr });}}try {await fetchData();} catch (err) {console.error(err.message);console.error('Original source:', err.cause.message);}
nodejs
Breakdown
1
{ cause: dbErr }
Passes the original error as metadata to the new Error instance.
2
err.cause
Accesses the nested error object for deep diagnostic analysis.