情况:
我正在使用其他属性(时间戳,标识)扩展Node.js(v。8.4.0)错误对象,然后扩展此对象以获得更精细的错误处理。
class MyError extends Error {
constructor (msg) {
super(msg);
this.id = uuid();
this.timestamp = Date.now();
// I reckon this can be replaced by this.init(this) ?
this.name = this.constructor.name;
Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
}
init (self) {
self.name = self.constructor.name;
Error.captureStackTrace && Error.captureStackTrace(self, self.constructor);
}
}
我希望能够在子错误中不再重复
Error.captureStackTrace
和this.name
调用。因此,我创建了一个在子级中使用的初始化函数,如下所示:class GranularError extends MyError {
constructor (msg) {
super(msg);
this.type = "error";
this.status = 500;
this.code = "internalServerError";
super.init(this);
}
}
GranularError
然后将再次扩展以获取MoreGranularError
等。这就是为什么我想将其保持DRY的原因。问题:
抛出GranularError或MoreGranularError时,失败并显示
TypeError: (intermediate value).init is not a function
我主要阅读了以下资料,但无法将其应用于问题。任何帮助表示赞赏。
Call parent function which is being overridden by child during constructor chain in JavaScript(ES6)
Parent constructor call overridden functions before all child constructors are finished
http://2ality.com/2015/02/es6-classes-final.html#referring_to_super-properties_in_methods
最佳答案
我不知道您遇到了什么错误,但是没有必要创建init
函数。 this.name
和Error.captureStack
的东西也将在子级中工作,因为this
引用了子级实例。
换句话说,您正在尝试解决不存在的问题。
class MyError extends Error {
constructor (msg) {
super(msg);
this.id = Math.random();
this.timestamp = Date.now();
this.name = this.constructor.name;
Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
}
}
class GranularError extends MyError {
constructor (msg) {
super(msg);
this.type = "error";
this.status = 500;
this.code = "internalServerError";
}
}
console.dir(new GranularError("this is the error message"));
关于javascript - 如何在子构造函数中使用ES6 super调用父方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46590566/