Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

10
  • 21
    You could move the this.name = 'MyError' outside of the function and change it to MyError.prototype.name = 'MyError'. Commented Jun 11, 2011 at 22:42
  • 43
    This is the only correct answer here, although as a matter of style, I'd probably write it like this. function MyError(message) { this.message = message; this.stack = Error().stack; } MyError.prototype = Object.create(Error.prototype); MyError.prototype.name = "MyError"; Commented Oct 2, 2012 at 10:10
  • 14
    I'd add MyError.prototype.constructor = MyError too. Commented Apr 22, 2014 at 13:01
  • 6
    MyError.prototype = Object.create(Error.prototype); Commented Nov 27, 2014 at 17:37
  • 4
    @Silverspur The act of assigning MyError.prototype = Object.create(Error.prototype) (or new Error) is overwriting all members of MyError.prototype. Therefore MyError.prototype.constructor is actually Error.prototype.constructor, since we just assigned the entire Error.prototype to MyError.prototype. This is a side effect of JavaScript not really an object-oriented language, but a prototypal language. So this is why we assign MyError.prototype.constructor = MyError back to the MyError constructor function. Commented Mar 23, 2017 at 2:04