Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Last active April 17, 2016 18:23
Show Gist options
  • Save ernestlv/ec23582ad01af5019ad930b2dd7797a3 to your computer and use it in GitHub Desktop.
Save ernestlv/ec23582ad01af5019ad930b2dd7797a3 to your computer and use it in GitHub Desktop.
safe invokes a given function by wraping it in a try/catch, function must be a member of the supplied object. Useful in some contexts like analytic functions in unit tests.
function attempt(obj, p, fnFail){
var fn = function(){};
if (obj && typeof obj[p] === 'function'){
fn = function(){
try {
return this[p].apply(this, [].slice.apply(arguments));
}catch(e){
return typeof fnFail === 'function' ? fnFail(e, p, obj) : console.error('attempt fail:', this['__id__'] || '', p, e);
}
}.bind(obj);
}else{
console.log('attempt warning not a function:', p);
}
return fn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment