Error() 构造函数
语法
¥Syntax
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)
注意:可以使用或不使用
new
来调用Error()
。两者都会创建一个新的Error
实例。¥Note:
Error()
can be called with or withoutnew
. Both create a newError
instance.
参数
¥Parameters
message
Optional-
人类可读的错误描述。
options
Optional-
具有以下属性的对象:
fileName
Optional Non-standard-
引发此错误的文件的路径,反映在
fileName
属性中。默认为包含调用Error()
构造函数的代码的文件的名称。 lineNumber
Optional Non-standard-
文件中出现错误的行号,反映在
lineNumber
属性中。默认为包含Error()
构造函数调用的行号。
示例
函数调用或新建
¥Function call or new construction
当 Error
像函数一样使用时,即没有 new
,它将返回一个 Error
对象。因此,仅调用 Error
将产生与通过 new
关键字构造 Error
对象相同的输出。
¥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!');
重新抛出错误并给出原因
¥Rethrowing an error with a cause
有时捕获错误并用新消息重新抛出它是有用的。在这种情况下,你应该将原始错误传递到新 Error
的构造函数中,如图所示。
¥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.
省略选项参数
¥Omitting options argument
如果 options
是一个对象,JavaScript 仅尝试读取 options.cause
— 这避免了与其他非标准 Error(message, fileName, lineNumber)
签名的歧义,后者要求第二个参数是字符串。如果省略 options
,传递原始值作为 options
,或传递不带 cause
属性的对象,则创建的 Error
对象将没有 cause
属性。
¥JavaScript only tries to read options.cause
if options
is an object — this avoids ambiguity with the other non-standard Error(message, fileName, lineNumber)
signature, which requires the second parameter to be a string. If you omit options
, pass a primitive value as options
, or pass an object without the cause
property, then the created Error
object will have no cause
property.
// Omitting options
const error1 = new Error("Error message");
console.log("cause" in error1); // false
// Passing a primitive value
const error2 = new Error("Error message", "");
console.log("cause" in error2); // false
// Passing an object without a cause property
const error3 = new Error("Error message", { details: "http error" });
console.log("cause" in error3); // false
规范
Specification |
---|
ECMAScript Language Specification # sec-error-constructor |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also
Error
的 Polyfill,在core-js
中支持cause
throw
try...catch
- v8.dev 上的 错误原因 (2021)