在大型公共图书馆(pg-promise)重构ES6的自定义错误后,我得到一些奇怪的报告,在某些特殊情况下自定义错误可能无法正确实例化,我还没有#39经过多次尝试后,我们能够重现。
如果某人有实施自定义错误的经验,请告诉我所做的重构是否正确1:1,或者我是否错过了某些内容。
原始ES5代码
function CustomError(errCode) {
var temp = Error.apply(this, arguments);
temp.name = this.name = 'CustomError';
this.stack = temp.stack;
this.code = errCode;
}
CustomError.prototype = Object.create(Error.prototype, {
constructor: {
value: CustomError,
writable: true,
configurable: true
}
});
CustomError.prototype.toString = function () {
console.log('errCode:', this.code);
};
CustomError.prototype.inspect = function () {
return this.toString();
};
重构ES6代码:
class CustomError extends Error {
constructor(errCode) {
super();
Error.captureStackTrace(this, CustomError);
this.code = errCode;
}
}
CustomError.prototype.toString = function () {
console.log('errCode:', this.code);
};
CustomError.prototype.inspect = function () {
return this.toString();
};
两个示例都需要在任何Node.js 4.x及更高版本下工作相同,实例化为:
const error = new CustomError(123);
console.log(error);
根据错误报告,有时候这样的类型应该是在没有正确的this
上下文的情况下创建的,或者更准确地说,错误是:can't use 'code' of undefined
在toString
内部
更新
查看本文后:Custom JavaScript Errors in ES6及其示例:
class GoodError extends Error {
constructor(...args) {
super(...args)
Error.captureStackTrace(this, GoodError)
}
}
似乎传递这样的论点就是我所缺少的。但是,考虑到:,如何正确更新我的CustomError
课程以做同样的事情
...args
在Node.js 4.x中不起作用,所以我无法使用它errCode
答案 0 :(得分:1)
我相信这相当于您的ES5代码
<g:HorizontalPanel>
<g:Anchor ui:field="A"/>
<g:HTML ui:field="B" />
<g:Anchor ui:field="C" />
<g:HTML ui:field="D" />
</g:HorizontalPanel>
您可以将class CustomError extends Error {
constructor( errCode ){
super(...arguments);
this.name = "CustomError";
this.code = errCode;
}
toString(){
console.log('errCode:', this.code);
}
inspect(){
return this.toString();
}
}
替换为
super(...arguments)