Lone Learner
Lone Learner

Reputation: 20688

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

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?

Upvotes: 6

Views: 2914

Answers (2)

Fabian Madurai
Fabian Madurai

Reputation: 355

window.onerror is like a global try/catch block. Use try/catch to target specific blocks where you know you are likely to get an error.

the window.onerror is a general case. One thing I noticed is that the function you assign to window.onerror to handle the error, should be defined above the code that calls it or you might get a function undefined error.

Upvotes: 0

Lapsio
Lapsio

Reputation: 7084

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

Upvotes: 1

Related Questions