I noticed a strange behavior while defining custom error objects in Javascript:
function MyError(msg) {
Error.call(this, msg);
this.name = \"MyError\
You can use Error.captureStackTrace for filtering out unneeded line in stack trace.
function MyError() {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'MyError';
this.message = tmp.message;
/*this.stack = */Object.defineProperty(this, 'stack', { // getter for more optimizy goodness
get: function() {
return tmp.stack;
}
});
Error.captureStackTrace(this, MyError); // showing stack trace up to instantiation of Error excluding it.
return this;
}
var IntermediateInheritor = function() {},
IntermediateInheritor.prototype = Error.prototype;
MyError.prototype = new IntermediateInheritor();
var myError = new MyError("message");
console.log("The message is: '"+myError.message+"'"); // The message is: 'message'
console.log(myError instanceof Error); // true
console.log(myError instanceof MyError); // true
console.log(myError.toString()); // MyError: message
console.log(myError.stack); // MyError: message \n
// <stack trace ...>