Skip to content

Instantly share code, notes, and snippets.

@heroqu
Created July 11, 2016 10:34
Show Gist options
  • Save heroqu/e2e06a93348c3aeb530bf8d6cfdf66d8 to your computer and use it in GitHub Desktop.
Save heroqu/e2e06a93348c3aeb530bf8d6cfdf66d8 to your computer and use it in GitHub Desktop.
Making custom error type in Javascript
// 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