Created
February 12, 2014 07:28
-
-
Save jcayzac/8951348 to your computer and use it in GitHub Desktop.
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
| // Proper exceptions in JS: | |
| function MakeErrorClass(name, parent) { | |
| parent = parent || Error | |
| var cls = function(message) { | |
| parent.call(this, arguments) | |
| if (Error.captureStackTrace) | |
| Error.captureStackTrace(this, this.constructor) | |
| else | |
| this.stack = [name].concat(Error().stack.split('\n').slice(3)).join('\n') | |
| this.message = message | |
| Object.freeze(this) | |
| } | |
| cls.prototype = Object.create(parent.prototype, {name: {value: name, enumerable: true}}) | |
| cls.prototype.constructor = cls | |
| return cls | |
| } | |
| // Example: | |
| var MyError = MakeErrorClass('MyError') | |
| var SubError = MakeErrorClass('SubError', MyError) | |
| try { | |
| throw new SubError('foo') | |
| } catch (e) { | |
| console.log(e instanceof MyError ? 'Got a MyError!' : 'Got an unknown error!') | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment