-
-
Save eliperelman/1566120 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
define(function () { | |
var HttpError = function (msg, code) { | |
var ex = new Error(msg || 'Unknown HTTP error'); | |
ex.code = code; | |
ex.toString = function() { | |
return 'Error: ' | |
+ (this.code ? '' : '(' + this.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 | |
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