Last active
December 28, 2016 02:06
-
-
Save mbrowne/fe45db61cea7858d11be933a998926a8 to your computer and use it in GitHub Desktop.
Subclass error in JS with native-like console output
This file contains 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
function CustomError(message) { | |
if (!(this instanceof CustomError)) { | |
throw new TypeError("Constructor 'CustomError' cannot be invoked without 'new'"); | |
} | |
var err; | |
if (Object.setPrototypeOf) { | |
err = new Error(message); | |
Object.setPrototypeOf(err, CustomError.prototype); | |
} | |
else { | |
err = this; | |
} | |
if (Error.captureStackTrace) { | |
Error.captureStackTrace(err, CustomError); | |
} | |
return err; | |
} | |
CustomError.prototype = Object.create(Error.prototype); | |
CustomError.prototype.name = 'CustomError'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: One possible downside of this approach is that errors appear in the console as
Error: ...
rather thanCustomError: ...
. But otherwise they appear just the same as errors extended using ES6 classes (class CustomError extends Error {}
).