Created
May 24, 2015 05:29
-
-
Save ehsanullahjan/dc596706c8387d6c6229 to your computer and use it in GitHub Desktop.
Custom errors in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function IllegalArgumentError(message) { | |
Error.call(this, message); | |
this.name = 'IllegalArgumentError'; | |
} | |
IllegalArgumentError.prototype = new Error(); | |
IllegalArgumentError.prototype.constructor = IllegalArgumentError; |
Three rules of proper prototypal inheritance in JavaScript:
- Remember to call super constructor function (line #2)
- Set prototype to instance of parent constructor (line #6)
- "Fix" the constructor (line #7).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Custom errors created following this pattern will behave exactly like the built-in errors. For example, when thrown,
IllegalArgumentError
will print stack trace exactly how throwing the built-inError
would.