【发布时间】:2018-03-17 08:44:54
【问题描述】:
情况:
我正在扩展 Node.js (v. 8.4.0) 带有附加属性(时间戳、id)的错误对象,然后扩展此对象以获得更精细的错误处理。
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 调用。所以我创建了一个 init 函数,我在孩子中使用这样的函数:
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
【问题讨论】:
-
您的代码似乎在 Chrome (jsfiddle.net/Lrfxum4a) 中运行顺畅。你用的是什么环境? (我猜是Node,基于
uuid?什么版本?) -
是的,它是 Node 8.4.0。我已经将它添加到开头。感谢您的评论。它似乎在 Chrome 上运行良好,这确实很奇怪。
标签: javascript node.js ecmascript-6 super es6-class