【发布时间】:2015-08-04 19:21:12
【问题描述】:
当通过 BabelJS 运行这个 sn-p 时:
class FooError extends Error {
constructor(message) {
super(message);
}
}
let error = new FooError('foo');
console.log(error, error.message, error.stack);
输出
{}
这不是我所期望的。跑步
error = new Error('foo');
console.log(error, error.message, error.stack);
生产
{} foo Error: foo
at eval (eval at <anonymous> (https://babeljs.io/scripts/repl.js?t=2015-05-21T16:46:33+00:00:263:11), <anonymous>:24:9)
at REPL.evaluate (https://babeljs.io/scripts/repl.js?t=2015-05-21T16:46:33+00:00:263:36)
at REPL.compile (https://babeljs.io/scripts/repl.js?t=2015-05-21T16:46:33+00:00:210:12)
at Array.onSourceChange (https://babeljs.io/scripts/repl.js?t=2015-05-21T16:46:33+00:00:288:12)
at u (https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js:28:185)
这正是我想要的扩展错误。
我的目标是将Error 扩展为各种子类,并在bluebird 的catch 匹配中使用它们。到目前为止,这一切都失败了。
为什么子类没有显示消息或堆栈跟踪?
编辑: using Chrome's built-in subclassing(感谢@coder)完美运行。这不一定是 Babel 特有的,如以下示例(来自@loganfsmyth on Babel's gitter feed)所示:
// Works
new (function(){
"use strict";
return class E extends Error { }
}());
// Doesn't
new (function(){
"use strict";
function E(message){
Error.call(this, message);
};
E.prototype = Object.create(Error);
E.prototype.constructor = E;
return E;
}());
【问题讨论】:
-
我认为这不是 Babel 问题。如果您使用旧方法来扩展错误,您会得到相同的缺失堆栈(在 Chromium41 上)。
-
你能确认你使用的浏览器吗?似乎适用于 chrome v42 jsfiddle.net/5e3kakqj
-
Chrome 42 上的@coder 也是如此。您的示例有效,但 Babel 版本无效。
-
@dystroy 你是对的。包括某人在 babel 的 gitter 上提出的一个最小示例,它显示了简单的假继承失败和真正的 ES6 继承工作。
标签: javascript ecmascript-6 babeljs