For some reason it looks like constructor delegation doesn’t work in the following snippet:
function NotImplementedError() {
Error.apply(this, arguments);
}
NotImplementedError.prototype = new Error();
var nie = new NotImplementedError("some message");
console.log("The message is: '"+nie.message+"'")
Running this gives The message is: ''. Any ideas as to why, or if there is a better way to create a new Error subclass? Is there a problem with applying to the native Error constructor that I don’t know about?
Update your code to assign your prototype to the Error.prototype and the instanceof and your asserts work.
However, I would just throw your own object and just check the name property.
Edit based on comments
After looking at the comments and trying to remember why I would assign prototype to
Error.prototypeinstead ofnew Error()like Nicholas Zakas did in his article, I created a jsFiddle with the code below:The console output was this.
This confirmes the "problem" I ran into was the stack property of the error was the line number where
new Error()was created, and not where thethrow eoccurred. However, that may be better that having the side effect of aNotImplementedError.prototype.name = "NotImplementedError"line affecting the Error object.Also, notice with
NotImplementedError2, when I don’t set the.nameexplicitly, it is equal to "Error". However, as mentioned in the comments, because that version sets prototype tonew Error(), I could setNotImplementedError2.prototype.name = "NotImplementedError2"and be OK.