JavaScript Error cause and Custom Error Context
Quick answer
An Error may carry a cause so a higher-level failure preserves information about the original reason. A custom error type can express a domain-specific failure contract.
How it works
Use new Error(message, {cause: original}) to wrap a caught value. Cause is optional and may be any value, not necessarily Error. As a preview of classes, class InputError extends Error defines an Error subtype; super initializes the inherited Error object and its message. Classes are covered later. Avoid exposing nested sensitive details to users.
const original = new RangeError("size");const wrapped = new Error("Cannot load item", {cause: original});console.log(wrapped.message, wrapped.cause === original);Expected output in Node.js:
Cannot load item trueCause retains the same original object identity.
class InputError extends Error { constructor(message) { super(message); this.name = "InputError"; } }const e = new InputError("bad count");console.log(e.name, e instanceof Error);Expected output in Node.js:
InputError trueThe subclass inherits Error behavior and explicitly sets its name.
Common mistakes
Wrapping an exception without retaining its original cause can make diagnosis harder. Do not depend on a portable stack trace format.
Practice
Wrap a synthetic low-level failure with a higher-level message and verify the original cause remains reachable.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Error cause and Custom Error Context — Knowledge Check
Apply the taught concept and predict the output.
What is the type constraint on Error cause?
Why preserve the original cause when wrapping an error?
Is the exact text layout of Error.stack a portable format to parse?
What is the exact console output in JavaScript Error cause and Custom Error Context example 1?
const original = new RangeError("size");const wrapped = new Error("Cannot load item", {cause: original});console.log(wrapped.message, wrapped.cause === original);What is the exact console output in JavaScript Error cause and Custom Error Context example 2?
class InputError extends Error { constructor(message) { super(message); this.name = "InputError"; } }const e = new InputError("bad count");console.log(e.name, e instanceof Error);