What is error wrapping (or error chaining), and how does the Error class's 'cause' property support it in modern Node.js?
Short answer
Error wrapping catches a lower-level error and re-throws a new, higher-level error that adds context relevant to the current layer of the application, while preserving the original error so its details aren't lost -- the standardized 'cause' option (available via `new…
Advertisement
AModel answer
Error wrapping catches a lower-level error and re-throws a new, higher-level error that adds context relevant to the current layer of the application, while preserving the original error so its details aren't lost -- the standardized 'cause' option (available via `new Error(message, { cause: originalError })`) provides a built-in way to do this without needing a custom convention, letting downstream code and logging tools walk the full chain of causation from a high-level error back to its root cause.
async function getUserProfile(id) {
try {
return await db.users.findById(id);
} catch (err) {
throw new Error('Failed to load user profile', { cause: err }); // preserves the original error
}
}
// Later, when logging or debugging:
console.error(err.message, 'caused by:', err.cause?.message);Real-world example
A team debugging a confusing 'Failed to load user profile' error in production is able to trace it back to the actual root cause -- a database connection timeout -- because the error was wrapped using the 'cause' option rather than the original error being discarded and replaced entirely.
Likely follow-ups
- How did teams handle this same error-wrapping need before the standardized 'cause' property was introduced?
- How do logging libraries and error-tracking tools (like Sentry) typically surface and display a full error cause chain?
Related topics