2

I need to run third party JS to scan jserrors. I am running the following in chrome's console

window.onerror = function(errorMsg, url, lineNumber) {
  alert(errorMsg);
}

throw new Error('foo');

I expect both the console to inform me of the error and a alert to pop up displaying the error message. The alert is never fired, and I assume the event is not being fired. why not?

MrBrightside
  • 593
  • 2
  • 10
  • 22
  • I cannot reproduce the problem (using [this fiddle](http://jsfiddle.net/bS3kg/)). I'm using Chromium 28.0.1500.71 Ubuntu. – ComFreek Sep 03 '13 at 16:26
  • Thanks for the comment, I'm not sure how jsFiddle deals with this but, the part that causes the issue I believe is injecting this js after the page is loaded. If you open the console in chrome and paste the code in it wil not fire – MrBrightside Sep 03 '13 at 16:30
  • Adding an error handler by inserting a ` – ComFreek Sep 03 '13 at 16:40
  • @ComFreek - "thus I think that the Dev Console changes the behavior somehow." I think you're exactly right. http://stackoverflow.com/questions/17534054/chrome-will-an-error-in-code-invoked-from-the-dev-console-trigger-window-onerro – MrBrightside Sep 03 '13 at 16:42
  • If you post that as an anwer I would be glad to accept it as the answer – MrBrightside Sep 03 '13 at 16:43
  • You've also given me a good way to test my code (jfiddle) thanks – MrBrightside Sep 03 '13 at 16:43
  • Does this answer your question? [Chrome: Will an error in code invoked from the dev console trigger window.onerror?](https://stackoverflow.com/questions/17534054/chrome-will-an-error-in-code-invoked-from-the-dev-console-trigger-window-onerro) – Peter Noges Mar 13 '21 at 17:24

1 Answers1

4

The Chrome Developer Console won't call the user-defined error event listener if the error is thrown immediately (according to this answer by Paul S.).

Throwing the error "just in time":

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

Throwing the error deferred:

> window.setTimeout(function() {throw new Error()}, 0);
xxxx
error!
Uncaught Error

(xxxx is the specific return value of setTimeout())


Here is the original code snippet which led me to the point that the Chrome Dev Console changes the internal behaviour somehow:
// #btn is a simple button
document.getElementById("btn").addEventListener("click", function () {
    var script = document.createElement("script");
    script.innerHTML = "window.onerror=function(){alert('An error occurred!');};throw new Error('42');";
    document.head.appendChild(script);
});

This code is to be executed in a normal HTML file.

Community
  • 1
  • 1
ComFreek
  • 29,044
  • 18
  • 104
  • 156