Last active
August 29, 2015 14:05
-
-
Save grncdr/564e90adca19aba6d939 to your computer and use it in GitHub Desktop.
Custom JS errors
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
var inherits = require('inherits'); | |
inherits(CustomError, Error); | |
function CustomError () { | |
this.constructor.super_.apply(this, arguments); | |
this.name = this.constructor.name; | |
if (Error.captureStackTrace) { | |
Error.captureStackTrace(this, this.constructor); | |
} | |
} | |
// And that's it. If you want to make a large variety of errors without the boilerplate, inherit from CustomError: | |
inherits(AnotherError, CustomError); | |
function AnotherError (specialErrorData) { | |
this.errorData = specialErrorData; | |
this.constructor.super_.call(this, this._formatMessage()); | |
} | |
AnotherError.prototype._formatMessage = function () { | |
return this.errorData.map(function (e) { return e.message }).join(', '); | |
} |
Although this works as I'd expect custom errors to work, it introduces overhead in the error constructors and an extra dependency when running on the client side. The main problem with extending errors (as well as another things) in JS is the inability to inherit constructors which I think is not fixable in the current state of JS.
Thanks for your input but I think, i'll stick with my solution of "annotating" errors:
function custom_error(err) {
err.name = "CustomError";
err.code = "ECUSTOM" //or whatever, e.g. could be used to hold HTTP error codes
return err;
}
/*
...
*/
throw custom_error(new Error("blablabla");
This might be a hack but it's reliable, has no external dependencies and very low overhead.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is one way of doing things. Other nice ready-to-use libraries inclue
verror
which has sane default behaviours, and @Raynos'serror
which allows including arbitrary data with your errors (as well as nice message format strings).I went with the above approach in our codebase because I wanted to share behaviour across all of our custom errors (a .toJSON method so we can JSON.stringify(error)) and message formatting wasn't that important to us.