It is sometimes useful to catch an error and re-throw it with a new message. In this case you should pass the original error into the constructor for the new Error, as shown
// Cleanup title
try {
connectToDatabase();
} catch (err) {
throw new Error("Connecting to database failed.", { cause: err });
}
// With structured cause
function makeRSA(p, q) {
if (!Number.isInteger(p) || !Number.isInteger(q)) {
throw new Error("RSA key generation requires integer inputs.", {
cause: { code: "NonInteger", values: [p, q] },
});
}
if (!areCoprime(p, q)) {
throw new Error("RSA key generation requires two co-prime integers.", {
cause: { code: "NonCoprime", values: [p, q] },
});
}
// rsa algorithm…
}
Please provide your feature request
Errors are often rethrown with property
cause
to provide additional context. RUM JSErrors should include this as a standard field.From documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause