javascript / intermediate
Snippet
Enhanced Debugging with Error Chaining
The 'cause' property allows you to wrap errors with high-level context while preserving the original error for easier debugging and stack trace analysis.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
async function fetchData() {try {await db.connect();} catch (err) {throw new Error('Database connection failed', { cause: err });}}// Accessing the original errortry {await fetchData();} catch (e) {console.error(e.message);console.error('Original cause:', e.cause);}
nodejs
Breakdown
1
{ cause: err }
Passes the original error object into the second argument of the Error constructor.
2
e.cause
Retrieves the underlying error that triggered the current exception.