50

I am trying to add an onerror event to my website.

window.onerror = function() {
    alert("an error");
}

But all I receive is:

notThere();
ReferenceError: notThere is not defined

What am I missing?

Browser: Chrome 26.0.1410.64 m

Steps to reproduce:

  • add the code to the console.
  • add notThere() to the console
Dinkheller
  • 4,631
  • 5
  • 39
  • 67

3 Answers3

62

window.onerror is not triggered when the console directly generates an error. It can be triggered via setTimeout though, e.g., setTimeout(function() { notThere(); }, 0);

Possible duplicate: Chrome: Will an error in code invoked from the dev console trigger window.onerror?

Community
  • 1
  • 1
wrschneider
  • 17,913
  • 16
  • 96
  • 176
43

The window.onerror works in Chrome (see jsfiddle - http://jsfiddle.net/PWSDF/), but apparently not in the console - which makes some sense.

Lachezar
  • 6,523
  • 3
  • 33
  • 34
  • 67
    what sense does it make? – Vlas Bashynskyi Jul 12 '16 at 10:28
  • 4
    I guess, it would hijack errors instead of displaying them in the console. – Lachezar Jul 20 '16 at 14:07
  • I assume it's for security and isolation. So the site doesn't have access to what the user is tampering with on the developer console. Not mentioning it would clutter the possible exception capturing or cause undefined behavior catching errors that didn't happen organically on the site. – p0358 Nov 07 '20 at 07:45
  • So no error that logs using the console can be captured? I'm not getting anything with `window.location.href = "not://anywhere";` ... it just logs to the console and I can't capture it. How many errors are impossible to get like this? – RaisinBranCrunch Dec 04 '20 at 19:02
  • @RaisinBranCrunch It can capture any exception that did NOT originate from the console (in some sense, the REPL loop acts as its own exception handler). However, errors that don't throw an exception will not fire an event. Your example fails because there is no uncaught exception. Similarly, this code does not trigger an alert: `try {window.location.href = "not://anywhere";} catch{alert("NO");}` . – Brian Nov 09 '22 at 16:26
26

Some other reasons that you may not be able to handle errors in window.onerror (apart from the mentioned ones):

  • Another library sets window.onerror after you.
  • If you are using Angular, errors wont pass through window.onerror. You have to handle them using this factory:

        .factory('$exceptionHandler', function() {
            return function errorCatcherHandler(exception, cause) {
                console.error(exception);
                if (window.OnClientError) window.OnClientError(exception);
            };
        })
    

See:

https://docs.angularjs.org/api/ng/service/$exceptionHandler

http://bahmutov.calepin.co/catch-all-errors-in-angular-app.html

NoOne
  • 3,851
  • 1
  • 40
  • 47