Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between handling errors with window.onerror and try-catch block

Tags:

javascript

I am considering handling JavaScript runtime errors with window.onerror vs. try{...} catch(e){...} blocks.

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onerror states:

Note that some/many error events do not trigger window.onerror, you have to listen for them specifically.

It seems that both window.onerror and try{...} catch(e){...}can handle ReferenceError: http://jsfiddle.net/7RARf/

Also, both are incapable of handling SyntaxError: http://jsfiddle.net/UXVs2/

Apart from obvious differences between handling error using window.onerror and handling them try{...} catch(e){...} with like, try-catch allows us to handle an error gracefully, re-throw them, etc. whereas a window.onerror function does not, etc. what other differences exist between the two ways of handling errors? Are there any errors that can be handled with window.onerror but not with try{...} catch(e){...}? Vice versa?

like image 822
Lone Learner Avatar asked Oct 02 '13 15:10

Lone Learner


1 Answers

Yes - window.onerror can detect errors caused by browser workflow - try/catch operates only on limited part of executed js code. window.onerror may detect plugins issues or any errors caused by not strictly your code (libraries like jQ, APIs like YT API etc) - eg: you can't put asynchronous code supported by external library in try (without modifications in foreign code), you can't put script loading done by html tag into try (it's managed by browser) - window.onerror will fire when script file is damaged and can't be loaded to tag - window.onerror throws much more errors than catch is able to support - also it contains info about file and line. Disadvantage is that window.onerror gives only info - code is interrupted, using try/catch you can provide fallback behaviour and allow code to deal with situation - even if there were errors

you can use try/catch to catch syntax error but only if you're evaluating code form string :

try{
  eval('(function(){asdhaowd;;;;asd;!!!@#!@$lolzolololol]]]]]]]})()');
} catch(e){
  do sth();
}

It'll catch eval error (unexpected ']' or something before it) I'm using it on my site to detect damaged code uploaded by users. window.onerror is usefull only for debug - it can't prevent code from crash, when try can

like image 76
Lapsio Avatar answered Oct 13 '22 10:10

Lapsio