Created
July 11, 2016 10:34
-
-
Save heroqu/e2e06a93348c3aeb530bf8d6cfdf66d8 to your computer and use it in GitHub Desktop.
Making custom error type 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
| // Making custom error types | |
| // Taken from the comment at https://blog.getify.com/howto-custom-error-types-in-javascript/ | |
| // | |
| function makeErrorType() { | |
| var it = function (message) { | |
| if (!(this instanceof it)) { | |
| return new it(message); | |
| } | |
| this.message = message; | |
| this.stack = new Error(message).stack; | |
| } | |
| it.prototype = Object.create(Error.prototype); | |
| return it; | |
| } | |
| //////////////////////////// | |
| // in action: | |
| let MyError = makeErrorType(); | |
| let MyError2 = makeErrorType(); | |
| try { | |
| throw new MyError("some message"); | |
| } catch (err) { | |
| console.log(err.message); // some message | |
| console.log(err instanceof MyError); // true | |
| console.log(err instanceof MyError2); // false | |
| console.log(err instanceof Error); // true | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment