The Error()
constructor creates an error object.
The Error()
constructor creates an error object.
new Error() new Error(message) new Error(message, options) new Error(message, fileName) new Error(message, fileName, lineNumber) Error() Error(message) Error(message, options) Error(message, fileName) Error(message, fileName, lineNumber)
Note: Error()
can be called with or without new
. Both create a new Error
instance.
message
Optional
A human-readable description of the error.
options
Optional
An object that has the following properties:
cause
Optional
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 can be used to pass the original error.
fileName
Optional Non-standard
The value for the fileName
property on the created Error
object. Defaults to the name of the file containing the code that called the Error()
constructor.
lineNumber
Optional Non-standard
The value for the lineNumber
property on the created Error
object. Defaults to the line number containing the Error()
constructor invocation.
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.
const x = Error('I was created using a function call!') // above has the same functionality as following const y = new Error('I was constructed via the "new" keyword!')
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.
Desktop | Mobile | Server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | Deno | Node.js | |
Error |
1 |
12 |
1 |
6 |
4 |
1 |
4.4 |
18 |
4 |
10.1 |
1 |
1.0 |
1.0 |
0.10.0 |
fileName_parameter |
No |
No |
1 |
No |
No |
No |
No |
No |
4 |
No |
No |
No |
No |
No |
lineNumber_parameter |
No |
No |
1 |
No |
No |
No |
No |
No |
4 |
No |
No |
No |
No |
No |
options_cause_parameter |
93 |
93 |
91 |
No |
79 |
15 |
93 |
93 |
91 |
No |
15 |
17.0 |
1.13 |
16.9.0 |
Error
with modern behavior like support cause
is available in core-js
throw
try...catch
© 2005–2022 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error