Skip to content

Instantly share code, notes, and snippets.

@unscriptable
Created January 5, 2012 15:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save unscriptable/1565759 to your computer and use it in GitHub Desktop.
Save unscriptable/1565759 to your computer and use it in GitHub Desktop.
Example "subclass" of Error object
// AMD module wrapper.
define(function () {
function HttpError (msg, code) {
var ex;
msg = msg || 'Unknown HTTP error';
ex = new Error(msg); // not all browsers let us inherit, so we do it this way
ex.code = code;
ex.name = 'HttpError'; // thx @cjno! (http://twitter.com/cjno/status/154959746582056960)
ex.toString = function () {
var code = typeof this.code == 'undefined' ? '' : '(' + this.code + ') ';
return 'Error: ' + code + this.message;
};
return ex;
}
return HttpError;
});
throw new HttpError('session timed out', 405);
/*
this has several advantages over `throw 'session timed out'`, including:
1. browsers will include a full stack trace
2. other data (e.g. status code) can be carried along
3. you can sniff for the type of error via ex.name;
I had some issues with several browsers when trying to inherit from the
native Error object. That would be even better because then we could do
this:
if (ex instanceof HttpError) { ... }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment