使用ES6语法扩展Javascript中的错误&巴别塔 [英] Extending Error in Javascript with ES6 syntax & Babel
问题描述
我试图用ES6和Babel扩展Error。它没有用。
I am trying to extend Error with ES6 and Babel. It isn't working out.
class MyError extends Error {
constructor(m) {
super(m);
}
}
var error = new Error("ll");
var myerror = new MyError("ll");
console.log(error.message) //shows up correctly
console.log(myerror.message) //shows empty string
Error对象永远不会得到正确的消息集。
The Error object never get the right message set.
现在我在SO上看到了一些解决方案(这里举例说明),但它们似乎都非ES6 -y。如何以漂亮的ES6方式做到这一点? (这是在Babel工作)
Now I have seen a few solutions on SO (for example here), but they all seem very un-ES6-y. How to do it in a nice, ES6 way? (That is working in Babel)
推荐答案
根据KarelBílek的回答,我会对<$ c做一个小改动$ c> constructor :
Based on Karel Bílek's answer, I'd make a small change to the constructor
:
class ExtendableError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = (new Error(message)).stack;
}
}
}
// now I can extend
class MyError extends ExtendableError {}
var myerror = new MyError("ll");
console.log(myerror.message);
console.log(myerror instanceof Error);
console.log(myerror.name);
console.log(myerror.stack);
这将在堆栈中打印 MyError
,而不是泛型错误
。
This will print MyError
in the stack, and not the generic Error
.
它还会将错误消息添加到堆栈跟踪 - 这是从Karel的例子。
It will also add the error message to the stack trace - which was missing from Karel's example.
如果它可用,它还将使用 captureStackTrace
。
It will also use captureStackTrace
if it's available.
使用Babel 6,您需要 transform-builtin-extend ( npm )为此工作。
With Babel 6, you need transform-builtin-extend (npm) for this to work.
这篇关于使用ES6语法扩展Javascript中的错误&巴别塔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!