Last active
March 19, 2020 17:17
-
-
Save sagiavinash/368baf7e3f90fc354c44af9280689c88 to your computer and use it in GitHub Desktop.
Factory function for creating custom Error classes
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
/* 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