Created
January 5, 2012 15:39
-
-
Save unscriptable/1565759 to your computer and use it in GitHub Desktop.
Example "subclass" of Error object
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
// 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; | |
}); |
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
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