Skip to content

Instantly share code, notes, and snippets.

@letsgetrandy
Created November 19, 2014 16:36
Show Gist options
  • Save letsgetrandy/c1addc57823d9f8a9d6b to your computer and use it in GitHub Desktop.
Save letsgetrandy/c1addc57823d9f8a9d6b to your computer and use it in GitHub Desktop.
function Handler(fn) {
this.func = fn;
return this;
}
Handler.prototype.handle = function(errMsg, callback) {
this.exceptions[errMsg] = callback;
}
Handler.prototype.try = function(context) {
context = context || this;
try {
this.func.call(context);
} catch(e) {
if (this.exceptions[e.message]) {
this.exceptions[e.message].call(e, context);
} else {
throw e;
}
}
}
// example usage
new Handler(function() {
// do something risky here
}).handle('TypeError', function() {
// handle a type error here
}).handle('undefined is not a function', function() {
// you might have expected a member that's not there?
}).try();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment