Skip to content

Instantly share code, notes, and snippets.

@sagiavinash
Last active March 19, 2020 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagiavinash/368baf7e3f90fc354c44af9280689c88 to your computer and use it in GitHub Desktop.
Save sagiavinash/368baf7e3f90fc354c44af9280689c88 to your computer and use it in GitHub Desktop.
Factory function for creating custom Error classes
/* defintion */
const createErrorClass = (name, customConstructor = () => {}) => {
const ctx = {
[name]: class extends Error {
constructor(...args) {
super(name);
customConstructor(this, ...args);
Error.captureStackTrace(this, ctx[name]);
}
}
};
return ctx[name];
};
/* usage */
const DefinedError = createErrorClass('DefinedError', (e, message) => {
e.message = message;
});
function log() {
console.log((new (createErrorClass('InlineError'))()).stack);
console.log((new DefinedError('runtime error message')).stack);
console.log((new Error()).stack);
}
log();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment