Skip to content

Instantly share code, notes, and snippets.

@subtleGradient
Created October 7, 2009 16:40
Show Gist options
  • Select an option

  • Save subtleGradient/204192 to your computer and use it in GitHub Desktop.

Select an option

Save subtleGradient/204192 to your computer and use it in GitHub Desktop.
Function.safeTry = (function(){
var currentHandler;
var dispatchFakeEvent;
var currentHandlerResult;
if (document.addEventListener){
document.addEventListener("fakeEvents", function(){
currentHandler(); // execute the callback
}, false);
dispatchFakeEvent = function(){
var fakeEvent = document.createEvent("UIEvents");
fakeEvent.initEvent("fakeEvents", false, false);
document.dispatchEvent(fakeEvent);
};
}
else
if (document.attachEvent){
document.documentElement.fakeEvents = 0;
document.documentElement.attachEvent("onpropertychange", function(event){
if (event.propertyName == "fakeEvents")
currentHandler();
});
dispatchFakeEvent = function(){
document.documentElement.fakeEvents++; // fire the propertychange event
return currentHandlerResult;
};
}
return function(handler, shouldCatch){
if (shouldCatch) {
try{ currentHandlerResult = handler(); }
catch(e){ currentHandlerResult = e; }
}
else {
currentHandler = function(){
currentHandlerResult = handler();
};
dispatchFakeEvent();
}
return currentHandlerResult;
};
})();
Function.prototype.safeTry = function(){
return Function.safeTry(this);
};
// Function.safeTry(function(){
// console.log("Init: 1");
// DOES_NOT_EXIST++; // this will throw an error
// });
//
// Function.safeTry(function(){
// console.log("Init: 2");
// });
function PASS(){ console.log('PASS'); return 'Passed!'; }
function FAIL(){ console.log('FAIL'); DOES_NOT_EXIST++; }
// console.log( Function.safeTry(PASS) );
// console.log( Function.safeTry(FAIL) );
console.log( PASS.safeTry() );
console.log( FAIL.safeTry() );
// console.log( FAIL.safeTry() instanceof Error );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment