Skip to content

Instantly share code, notes, and snippets.

@Kambfhase
Last active December 18, 2015 11:09
Show Gist options
  • Save Kambfhase/5773165 to your computer and use it in GitHub Desktop.
Save Kambfhase/5773165 to your computer and use it in GitHub Desktop.
This is a simple way to detect critical erros in synchronous code. Not sure if genuis or stupid.
function detect( fn, err){
var flag = true;
setTimeout(function(){
if(flag) err();
},0);
fn();
flag = false;
}
// example with error
detect( function(){
({}).foo();
}, function(){
console.log("ZOMG, an error occured!");
});
// example without error
detect( function(){
return 1+1;
}, function(){
// wont be executed
console.log("ZOMG, an error occured!");
});
@mattsherman
Copy link

I've tested out the performance of this approach using jsperf.com. I determined two things...

  1. The detect() approach does not appear to actually detect errors, at least in the context of jsperf.com's test runner (please edit the test case on jsperf.com if I set something up wrong).
  2. For the case in which there is no error thrown, the standard try/catch approach is much, much faster.

http://jsperf.com/try-catch-vs-settimeout-error-detection

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment