Skip to content

Instantly share code, notes, and snippets.

@grncdr
Last active August 29, 2015 14:05
Show Gist options
  • 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(', ');
}
@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