【发布时间】:2018-07-03 15:51:36
【问题描述】:
我在我的应用程序中创建了一些自定义错误,我想稍后使用构造函数名称检查它们。问题是当我在我的类中扩展 Error 时,constructor.name 总是“Error”,而不是我实际给它的名字。
我正在做一些测试,并注意到错误类会发生这种情况,但我创建的任何其他自定义类都不会发生这种情况。 例如:
class CustomClass {
constructor(msg) {}
}
class OtherClass extends CustomClass {
constructor(msg) {
super(msg);
}
class CustomError extends Error {
constructor(msg) {
super(msg);
}
}
const e = new CustomError("There was an error");
const otherClass = new OtherClass("This is a class");
console.log(otherClass.constructor.name); // "OtherClass" <- ok!
console.log(e.constructor.name); // "Error" <- not ok! expected "CustomError"
有人知道为什么会这样吗?
我想我可以这样做:
class CustomError extends Error {
constructor(msg) {
super(msg);
}
getName() {
return "CustomError";
}
}
const e = new CustomError("There was an error");
if(e.getName() == "CustomError") {
// do stuff
}
然后我得到:TypeError: e.getName is not a function
- 有谁知道在扩展 Error 时是否可以覆盖构造函数名称?
- 另外,为什么我不能在我的 CustomError 错误类中声明和调用方法?
编辑
根据@samanime 的建议,我将节点版本更新为 8.8.1,并找到了部分解决方案。
稍微改变一下语法:
const FileSystemException = module.exports = class FileSystemException extends Error {
constructor(msg) {
super(msg);
}
getName() {
return "FileSystemException";
}
}
const e = new FileSystemException("There was an error");
// Running node app.js
console.log(e.constructor.name); // "FileSystemException"
console.log(e.getName()); // "FileSystemException"
// Running babel-node app.js
console.log(e.constructor.name); // "Error"
console.log(e.getName()); // "TypeError: e.getName is not a function"
不过,如果有人可以让它与 babel 一起工作,那就太棒了,这样我就可以使用 import/export 语句而不必等待 node v9.4 LTS。
使用:
节点 v8.8.1
babel-node v6.26.0 w/“es2015”和“stage-0”预设
谢谢!
【问题讨论】:
-
它在我的工作正常
标签: javascript node.js class constructor extend