Wrap an error with cause
A lower-level operation fails and a higher-level API needs to add actionable context while retaining the original failure.
JavaScript · Class
The Error constructor creates Error objects that describe failures. It accepts an optional message and an options object for preserving an underlying cause, and it can be called with or without new.
The Error constructor creates an Error object that describes a failure. It accepts an optional message and, in modern JavaScript, an options object whose cause property records the underlying value; it works with or without new, and the resulting object can be thrown or inspected.
new Error()
new Error(message)
new Error(message, options)
Error()
Error(message)
Error(message, options)| Name | Type | Description |
|---|---|---|
message | any | Optional human-readable description of the error. |
options | object | Optional object; its cause property identifies the specific underlying cause. |
A new Error object.
const error = new Error("Invalid configuration", {
cause: new TypeError("timeout must be a number"),
});
console.log(error.name); // "Error"
console.log(error.message); // "Invalid configuration"
console.log(error.cause instanceof TypeError); // trueCreates an Error with a human-readable message and preserves the underlying error as its cause.
A lower-level operation fails and a higher-level API needs to add actionable context while retaining the original failure.
Application code needs to signal invalid state or input to an enclosing try/catch boundary.
A diagnostic layer needs a standard object with a message for logging or inspection.
Error() creates an Error object, optionally using a human-readable message. The constructor may be called either as Error() or new Error(), and both forms create an Error instance.
Follow-up: How can an error preserve the original failure while adding context? Pass the original error as options.cause when constructing a new Error.
The first argument is message, an optional human-readable description. The second modern form is options, whose cause property stores the specific underlying cause for later inspection.
Follow-up: What happens when options lacks cause? The resulting Error has no cause property.
Error can be thrown after construction, then caught and inspected through properties such as name, message, and cause. A wrapper error can therefore add a more useful message while retaining the original cause.
Follow-up: How would you distinguish an Error from an arbitrary caught value? Use the documented Error.isError() static method when available.
AggregateErrorError.causeError.isError()Error.prototype.messageError.prototype.nameEvalErrorRangeErrorReferenceError