当通过BabelJS运行这段代码:扩展错误没有消息或堆栈跟踪
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
扩展成各种子类,并将它们用于蓝鸟的catch
匹配。到目前为止,这是失败的悲惨。
为什么子类不显示消息或堆栈跟踪?
编辑:using Chrome's built-in subclassing(感谢@coder)完美地工作。这是不特定于通天,不一定,如下面的示例(来自@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;
}());
我不认为这是一个巴别塔问题。如果您使用旧的方式来扩展错误,您将得到相同的缺失堆栈(在Chromium41上)。 –
你能确认你使用的浏览器吗? Chrome 42上的chrome v42 https://jsfiddle.net/5e3kakqj/ – coder
@coder也是如此。你的例子有效,但Babel版本没有。 – ssube