Skip to content

Instantly share code, notes, and snippets.

@grncdr
Last active August 29, 2015 14:05
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 grncdr/564e90adca19aba6d939 to your computer and use it in GitHub Desktop.
Save grncdr/564e90adca19aba6d939 to your computer and use it in GitHub Desktop.
Custom JS errors
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(', ');
}
@grncdr
Copy link
Author

grncdr commented Aug 26, 2014

This is one way of doing things. Other nice ready-to-use libraries inclue verror which has sane default behaviours, and @Raynos's error 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.

@selfawaresoup
Copy link

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