34

I'm trying to debug our handling of window.onerror. I've created a function that will throw an error (invoking another function that does not exist). I've tried calling this first function from Chrome's web development console - an error is reported in the console, but our window.error handling function does not seem to be called. (I've verified that window.onerror references our error handling code in the console).

Do errors within functions invoked in the dev console not trigger window.onerror?

UpTheCreek
  • 31,444
  • 34
  • 152
  • 221
  • duplicates: http://stackoverflow.com/questions/16192464/window-onerror-not-working-in-chrome , http://stackoverflow.com/questions/2384666/global-javascript-exception-handler-in-chrome – c69 Jul 08 '13 at 19:17
  • 3
    @c69 not sure if those are duplicates because _1._ `window.onerror` is now in _Chrome_. _2._ `window.onerror` is being triggered elsewhere in code. _3._ those questions don't talk about `console`. – Paul S. Jul 08 '13 at 19:20

1 Answers1

55

They don't (in Chrome where I tested), easy way to test is

window.onerror = function () {console.log('error!');};
throw new Error();
// Error

You can make them do it if you defer them, though

window.setTimeout(function() {throw new Error()}, 0);
// error!
// Uncaught Error
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • 2
    Oh that is interesting. Thanks for the clarification and workaround! – UpTheCreek Jul 08 '13 at 19:08
  • 2
    @RobW Interesting and may be applicable elsewhere +1, but then the question becomes "what is the origin of the `console`?" which can't be a simple answer if what you're saying is true otherwise _XHR_ wouldn't work from console. I think it is more likely that the `console` is wrapped in it's own `try..catch`. – Paul S. Jul 08 '13 at 19:13
  • 2
    @RobW - I thought that external scripts still invoked window.onerror, but that the error object was stripped of all useful info? Eg. The problem described in this question: http://stackoverflow.com/questions/5913978/cryptic-script-error-reported-in-javascript-in-chrome-and-firefox – UpTheCreek Jul 08 '13 at 19:15
  • @UpTheCreek Yes, you're right. I've deleted my previous incorrect comment. – Rob W Jul 08 '13 at 19:18
  • 1
    `debugger;` is your friend. // if you look at call stack, you will see that final eval is wrapped in two try catches (Cr28). – c69 Jul 08 '13 at 19:18
  • @c69 FYI when running `debugger;` in console on Chrome 81 there is only `(anonymous) (VM2240:1)` for the call stack and can't step into it. Not sure if I'm following correctly. – Rob Olmos May 12 '20 at 22:36