Browse topics

Error cause

Version
es2025
Since
es2022
Review
Draft

Summary#

Error constructors accept a cause option that links a new error to the failure behind it. You can add context while keeping the original value available.

Syntax#

js
throw new Error("operation failed", { cause: originalError });

Example#

js
function readPort() {
  try {
    return JSON.parse("{port}");
  } catch (cause) {
    throw new Error("invalid config", { cause });
  }
}

try {
  readPort();
} catch (error) {
  if (!(error instanceof Error)) throw error;
  console.log(error.message);
  console.log(error.cause instanceof SyntaxError);
  console.log(Object.keys(error).includes("cause"));
}

Expected output#

Text
invalid config
true
false

Common mistakes#

Pass { cause: error } as the second argument to retain the original error. Passing the error directly can pick up its existing cause, including an inherited one. The installed property is non-enumerable, so Object.keys and default JSON serialization omit it. Narrow cause before use because it can hold any value.

Version applicability#

ES2022 added the cause option. Earlier built-in Error constructors ignore the options argument.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0