Error() constructor
The Error constructor creates an error object.
Syntax
new Error()
new Error(message)
new Error(message, options)
new Error(message, fileName)
new Error(message, fileName, lineNumber)
Parameters
messageOptional-
A human-readable description of the error.
optionsOptional-
An object that has the following properties:
causeOptional-
A property indicating the specific cause of the error. When catching and re-throwing an error with a more-specific or useful error message, this property should be used to pass the original error.
fileNameOptional-
The value for the
fileNameproperty on the createdErrorobject. Defaults to the name of the file containing the code that called theError()constructor. lineNumberOptional-
The value for the
lineNumberproperty on the createdErrorobject. Defaults to the line number containing theError()constructor invocation.
Examples
Function call or new construction
When Error is used like a function, that is without new, it will return an Error object.
Therefore, a mere call to Error will produce the same output that constructing an Error object via the new keyword would.
// this...
const x = Error('I was created using a function call!')
// ...has the same functionality as this.
const y = new Error('I was constructed via the "new" keyword!')
Rethrowing an error with a cause
It is sometimes useful to catch an error and re-throw it with a new message.
In this case you should pass the original error into the constructor for the new Error, as shown.
try {
frameworkThatCanThrow();
} catch (err) {
throw new Error('New error message', { cause: err });
}
For a more detailed example see Error > Differentiate between similar errors.
Specifications
| Specification |
|---|
| ECMAScript Language Specification # sec-error-constructor |
Browser compatibility
BCD tables only load in the browser
See also
- A polyfill of
Errorwith modern behavior like supportcauseis available incore-js throwtry...catch- Error causes (v8.dev/features)