Error Cause Chains
You'll learn how to wrap errors with context while preserving the original error for debugging.
Why Error Causes Matter
When errors bubble up through multiple layers of your application, you often want to add context at each level without losing the original error information. Imagine a file-reading function that fails deep in your code — by the time that error reaches the user-facing layer, you want both the low-level "file not found" details and the high-level "failed to load user profile" context.
The cause Option
When constructing an Error, you can pass a second argument — an options object with a cause property that holds the original error:
function loadUserProfile(userId) {
try {
const data = readFile(`/users/${userId}.json`);
return JSON.parse(data);
} catch (originalError) {
throw new Error(
`Failed to load profile for user ${userId}`,
{ cause: originalError }
);
}
}
try {
loadUserProfile(42);
} catch (error) {
console.log(error.message);
// "Failed to load profile for user 42"
console.log(error.cause);
// Original error: "File not found: /users/42.json"
}
Building the Chain
Each error in the chain preserves the one below it. You can inspect error.cause, then error.cause.cause, and so on, creating a full diagnostic trail. This is invaluable when debugging production issues — you see exactly where things went wrong and what triggered it.
Key Takeaway: Use the { cause: originalError } option when throwing errors to wrap and preserve underlying errors, creating a traceable chain for debugging without losing valuable context at any layer.