How do I create a custom Error in JavaScript?

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?

23 Answers
23

Leave a Comment