Error cause in JavaScript
Lesson 33 of 38 in the JavaScript learning path.
How do I wrap a failed fetch without losing the original error?
The error cause option attaches the original exception to a new Error.
Replacing a TypeError with a generic message used to drop the stack you needed. cause keeps both.
Syntax & Parameters
throw new Error("Catalog unavailable", { cause });
Example
Interactive preview availablefunction loadSeats(raw) {
try {
const data = JSON.parse(raw);
if (typeof data.seats !== "number") {
throw new TypeError("seats must be a number");
}
return data.seats;
} catch (cause) {
throw new Error("Could not read the catalog payload", { cause });
}
}
try {
loadSeats("{");
} catch (error) {
const label = document.querySelector("#out");
label.textContent = error.message + " | " + error.cause.message;
}
Expected Output
Could not read the catalog payload | Unexpected end of JSON input
Line-by-Line Walkthrough
- JSON.parse throws on a broken payload.
- A seats value that is not a number throws TypeError.
- The catch receives that original error as cause.
- The new Error explains the catalog failure.
- The cause option keeps the original message.
- The page prints both messages.
- Do not catch and ignore the cause.
- Log cause when you report the wrapper.
Common Pitfalls & Security
This is easy to misuse.
- A wrapper without cause hides the parse error.
- Catching Error and throwing a string loses the stack.
- cause is not shown in every older console. Read it explicitly.
- Do not put secrets in the message. It will be logged.
Best Practices & Modern Standards
Wrap low-level failures with a sentence a teacher understands, and keep the original as cause.
Log both the wrapper and the cause in the server or the console.
Real-World Use
A catalog import reports that the payload could not be read and still preserves the JSON parser message for the person debugging it.
Frequently Asked Questions
Is cause a string?
It can be any value. Pass the caught error so the stack stays attached.
Do I have to wrap every throw?
No. Wrap at the boundary where the caller needs a clearer sentence.
How do I read it?
error.cause. Walk it if you wrap more than once.
Does this replace try?
No. You still catch the original error and then throw the wrapper.