admin管理员组

文章数量:1384639

I have following code to capture errors in javascript

<script type="text/javascript">
   window.onerror = function(msg, url, linenumber) {
      console.log('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
      return true;
   }
</script>

I opened chrome developer console and going to generate ReferenceError by random javascript code. Lets say:

person.run();  // person object does not exist

It throws Uncaught ReferenceError: person is not defined and printed in the console. But it is not captured by window.onerror. Why?

I have following code to capture errors in javascript

<script type="text/javascript">
   window.onerror = function(msg, url, linenumber) {
      console.log('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
      return true;
   }
</script>

I opened chrome developer console and going to generate ReferenceError by random javascript code. Lets say:

person.run();  // person object does not exist

It throws Uncaught ReferenceError: person is not defined and printed in the console. But it is not captured by window.onerror. Why?

Share Improve this question edited Oct 26, 2014 at 6:26 Fizer Khan asked Oct 26, 2014 at 6:13 Fizer KhanFizer Khan 93.1k30 gold badges147 silver badges156 bronze badges 5
  • the code should run without issues, are you sure you're not running person.run before you load the onerror, or is there something else that could interfere – Master Slave Commented Oct 26, 2014 at 6:21
  • I am just typing person.run() in chrome developer console. I want to know errors happen in chrome developer console(by your own try out codes) captured by window.onerror? – Fizer Khan Commented Oct 26, 2014 at 6:24
  • try window.alert(window.foo) – mplungjan Commented Oct 26, 2014 at 6:28
  • @mplungjan What do you mean? – Fizer Khan Commented Oct 26, 2014 at 6:30
  • Try something that might invoke a window error – mplungjan Commented Oct 26, 2014 at 8:21
Add a ment  | 

2 Answers 2

Reset to default 3

An event handler for runtime script errors.

Note that some/many error events do not trigger window.onerror, you have to listen for them specifically.

open this link this is use full for you:

https://developer.mozilla/en-US/docs/Web/API/GlobalEventHandlers.onerror

For console or for other browser app

 document.onerror=function (errorMsg, url, lineNumber,colNumder,error){
    console.log('OnError');
     return true
}

function consoleErrorTrap(call){
    try{
        return call();
    } catch(e){
        let event= new ErrorEvent('error',{error:e})
        document.dispatchEvent(event);
    }   
}

consoleErrorTrap(()=>{
    throw new Error()
})


本文标签: jquerywindowonerror and javascript console errorsStack Overflow