0 day streak
javascript / intermediate
Snippet

Contextual Debugging with Error Cause

The 'cause' property in the Error constructor allows you to wrap an original error inside a new one. This preserves the stack trace and context of the root cause while allowing for higher-level error messages.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
try {
try {
throw new Error('Database connection failed');
} catch (err) {
throw new Error('Login failed', { cause: err });
}
} catch (wrapperError) {
console.log(wrapperError.message); // 'Login failed'
console.log(wrapperError.cause.message); // 'Database connection failed'
}
Breakdown
1
throw new Error('Login failed', { cause: err });
Wraps the low-level error 'err' inside a user-facing error.
2
wrapperError.cause
Accesses the original error object for deeper investigation.
3
console.log(wrapperError.cause.message);
Retrieves the specific reason why the operation initially failed.