What you do is beautiful. This is Error , that is the problem.
In this line:
Error.prototype.constructor.apply(this, arguments);
... you call Error (indirectly) as a normal function call, and not as part of the new expression, but the defined behavior for Error , when you call it as a non-constructor function , is to create a new empty Error and return it (instead of filling this ).
Now, in the normal case, what you do with the prototype would do a standard check to see if it was called as a constructor ( if (this instanceof Error) ). Unfortunately, this does not seem to be the case, and any check that he uses to determine how it was called does not seem to immediately give in to what you are trying to do. Even this (this is just a test, not what you are actually doing):
MyError.prototype = Error.prototype;
... did not decide.
This answer to another question points to a possible workaround (basically, let Error create an object and then return this from MyError ):
function MyError(message) { var e = new Error(message);
Not surprisingly satisfactory, since you have to place your extensions directly on the object, and not use the prototype chain, but if Error refuses to play the ball, your options are a bit limited ...
source share