window.onerror not working in chrome

两盒软妹~` 提交于 2019-11-29 02:10:33

问题


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

回答1:


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




回答2:


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?




回答3:


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



来源:https://stackoverflow.com/questions/16192464/window-onerror-not-working-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!