Refer this, the Custom Errors in ES6 can be written as following:
class MyError extends Error {
constructor(message) {
super(message);
this.message = message;
this.name = 'MyError';
}
}
There is no need for
this.stack = (new Error()).stack;
trick thanks tosuper()
call.
However, I test it under Babel
class MyError extends Error {
constructor(message) {
super(message);
this.message = message;
this.name = 'MyError';
//this.stack = (new Error()).stack;
//Error.captureStackTrace(this, this.constructor.name);
}
}
var myerror = new MyError("test");
console.log(myerror.stack)
There is NO stack information unless the code this.stack = (new Error()).stack;
or Error.captureStackTrace(this, this.constructor.name);
is invoked.
But I test the above code snippet without this.stack = (new Error()).stack;
or Error.captureStackTrace(this, this.constructor.name);
under Chrome console
.
Output:
MyError: test
at MyError (<anonymous>:3:28)
at <anonymous>:12:19
at Object.InjectedScript._evaluateOn (<anonymous>:875:140)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:808:34)
at Object.InjectedScript.evaluate (<anonymous>:664:21)
Should I consider this is one defect on Babel
or Chrome issue? Or miss understanding the super()
?
Update
According to V8 codes, the stack
of Error
captureStackTrace = function captureStackTrace(obj, cons_opt) {
// Define accessors first, as this may fail and throw.
ObjectDefineProperty(obj, 'stack', { get: StackTraceGetter,
set: StackTraceSetter,
configurable: true });
Base on my understanding, since the stack
is one property of Error
, after supper()
is called, then it is not necessary to invoke captureStackTrace
in MyError
class. Am I missing something?