new Error() - JavaScript Error 对象
new Error()
Error()
构造函数创建一个错误对象。
语法
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
实例。
Parameters
message
OptionalA human-readable description of the error.
options
OptionalAn object that has the following properties:
cause
OptionalA 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-standardThe 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-standardThe value for the lineNumber
property on the created Error
object. Defaults to the line number containing the Error()
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.
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
的构造函数中,如图所示。
try { frameworkThatCanThrow(); } catch (err) { throw new Error("New error message", { cause: err }); }
For a more detailed example see Error > Differentiate between similar errors.
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!