Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Jun 14, 2013

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
You can’t perform that action at this time.