JavaScript Error cause
Example (before)
try {
// Create a JSON parse failure
JSON.parse("blablablabla");
} catch(err) {
let text = err.name + " " + err.message;
}
Try it Yourself »
Example (now)
try {
try {
// Create a JSON parse failure
JSON.parse("blablablabla");
} catch(err) {
// Create a new error and include the original one as the cause
throw Error("Failed to load JSON", {cause:err});
}
} catch(err){
let text = err.message + " " + err.cause;
document.getElementById("demo").innerHTML = text;
}
Try it Yourself »
Description
Starting from ECMAScript 2022, the Error constructor (and its subclasses like TypeError, SyntaxError, etc.) supports an optional {cause} property.
This allows you to create chained errors - where one error includes another as its cause.
Syntax
new Error(text, {cause:cause});
Return Value
| NONE |
See Also:
Browser Support
cause is a JavaScript 2022 feature.
ES 2022 is supported in all modern browsers since March 2023:
| Chrome 94 |
Edge 94 |
Firefox 93 |
Safari 16.4 |
Opera 79 |
| Sep 2021 | Sep 2021 | Oct 2021 | Mar 2023 | Oct 2021 |