JavaScript Intermediate Language Basics · 6 min read

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

Syntax
throw new Error("Catalog unavailable", { cause });

Example

Interactive preview available
errors.js
function 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

  1. JSON.parse throws on a broken payload.
  2. A seats value that is not a number throws TypeError.
  3. The catch receives that original error as cause.
  4. The new Error explains the catalog failure.
  5. The cause option keeps the original message.
  6. The page prints both messages.
  7. Do not catch and ignore the cause.
  8. 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.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…