Error.prototype.cause
The original reason for an error — so it is not lost when rethrowing.
Available since: ES2022
Syntax
new Error(message, { cause })Return value
anyThe original error, or any value passed as cause.
Examples
Wrapping a low-level error in a clearer one:
function loadConfig(text) {
try {
return JSON.parse(text);
} catch (error) {
throw new Error('Config is broken', { cause: error });
}
}
try {
loadConfig('{oops');
} catch (error) {
console.log(error.message);
console.log(error.cause.name);
}Output:
Config is broken
SyntaxErrorNotes
This way the user sees a clear message while the developer finds the technical details in cause.
See also
- Error — The base error class: created and thrown with throw.
- try...catch — Catches errors so the program does not stop.
- throw — Throws an error and stops the function.
In the tutorial
- Custom error classes — Your own errors in JavaScript: extending Error, the name property, extra data, checking with instanceof, rethrowing and cause.