A message like “Could not load settings” is nice for the person reading the log, but the real reason (a network error, a JSON parse error) is usually lost the moment you throw a new error from a catch. Since ES2022 the Error constructor takes a second argument with a cause, and I think every rethrow should use it.
You pass the caught error along, and it ends up on the new error as err.cause:
async function loadSettings() {
try {
const res = await fetch("/api/settings");
return await res.json();
} catch (err) {
throw new Error("Could not load settings", { cause: err });
}
}
try {
await loadSettings();
} catch (err) {
console.error(err.message); // Could not load settings
console.error(err.cause); // the original TypeError or SyntaxError
}
The outer message tells you what the code was trying to do, and cause tells you why it failed. Before this, people glued the old message onto the new one with string concatenation, which throws away the stack trace of the original.
The cause doesn’t have to be an error. MDN shows it with structured data, which is handy when other code has to react to the failure without parsing a sentence:
throw new Error("Invalid port", { cause: { code: "BAD_PORT", value: port } });
That freedom is also the caveat: when you read err.cause, don’t assume it’s an Error with a .message. Check it first. And like message, cause isn’t enumerable, so JSON.stringify(err) leaves it out. If you send errors to a logging service, copy the cause in yourself.
It works in Chrome and Edge 93, Firefox 91 and Safari 15, so MDN has listed it as Baseline widely available since March 2024.
Further reading: MDN: Error: cause, MDN: Error() constructor