Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Error: base exception object

Error creates the base error object with an optional message and cause, intended for throwing and chaining failures.

Version: ECMAScript 1 onward; cause option from ECMAScript 2022; example target: Node.js 24.22.2

Syntax

Error(message?, options?); new Error(message?, options?)

new Error(message?, options?) creates an error object; calling Error(...) without new has the same effect. If message is not undefined, it is converted to a string and stored as an own, non-enumerable message property. The inherited name property defaults to "Error".

If options is an object and has a cause property, its value is copied without conversion into an own, non-enumerable cause property. This preserves the original exception while adding context. Message conversion or the cause getter can throw. Error can be subclassed, and instanceof Error recognizes ordinary instances.

stack is a useful but non-standard host extension, and its format is not portable. Use subclasses for custom categories instead of parsing message text. Error has existed since ECMAScript 1; the cause option is standard since ECMAScript 2022.

Examples

function loadConfig() {
  try {
    JSON.parse("{");
  } catch (cause) {
    throw new Error("Could not load config", {cause});
  }
}

try {
  loadConfig();
} catch (error) {
  console.log(error.name, error.message);
  console.log(error.cause instanceof SyntaxError);
  console.log(Object.keys(error).join(",") || "(none)");
}
console.log(Error("plain") instanceof Error);

Result

Error Could not load config
true
(none)
true

Sources