Skip to content

Instantly share code, notes, and snippets.

@ehsanullahjan
Created May 24, 2015 05:29
Show Gist options
  • Save ehsanullahjan/dc596706c8387d6c6229 to your computer and use it in GitHub Desktop.
Save ehsanullahjan/dc596706c8387d6c6229 to your computer and use it in GitHub Desktop.
Custom errors in JavaScript
function IllegalArgumentError(message) {
Error.call(this, message);
this.name = 'IllegalArgumentError';
}
IllegalArgumentError.prototype = new Error();
IllegalArgumentError.prototype.constructor = IllegalArgumentError;
@ehsanullahjan
Copy link
Author

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-in Error would.

@ehsanullahjan
Copy link
Author

Three rules of proper prototypal inheritance in JavaScript:

  1. Remember to call super constructor function (line #2)
  2. Set prototype to instance of parent constructor (line #6)
  3. "Fix" the constructor (line #7).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment