0 day streak
javascript / intermediate
Snippet

Contextual Debugging with Error Cause

The 'cause' property in the Error constructor allows you to wrap lower-level errors in higher-level context without losing the original stack trace or error details. This is essential for debugging complex flows in Node.js backends.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
async function processOrder(orderId) {
try {
await db.save(orderId);
} catch (err) {
throw new Error(`Failed to process order ${orderId}`, {
cause: err
});
}
}
// Catching:
try {
await processOrder(123);
} catch (err) {
console.error(err.message); // High-level message
console.error(err.cause); // Original database error
}
nodejs
Breakdown
1
throw new Error(..., { cause: err });
Wraps the original error inside a new Error using the options object.
2
console.error(err.cause);
Accesses the underlying error that triggered the failure.