how to catch ALL javascript errors with [removed]?

2019-03-14 08:24发布

问题:

this question is a follow-up to javascript: how to display script errors in a popup alert? where it was explained how to catch regular javascript errors using:

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

I tried it and found out that dojo erros like this one:

TypeError: this.canvas is undefined         dojo.js (Row 446)

were not reported using this method, which leads me to my question:

How can I report all javascript errors using window.onerror (especially dojo errors)?

回答1:

It could be Dojo is using proper Error handling methods (i.e. try-catch blocks) which prevents the exception from bubbling up and reaching the window container, on which you have registered the error handler.

If so, there is no way for you to do this. No error is going past the catch block, so no error handler is being called.

As pointed out by the comments, you can also use browser-specific debugging APIs like the Venkman hook and do break-on-error -- a solution that usually only works for privileged code (thanks to @Sam Hanes).

You can also do On(require, 'error', function () {}); to add error handling on DOJO's asynchronous script loader -- another point mentioned in the comments by @buggedcom



回答2:

you can write code like this:

var goErrHandler=window.onerror;
goErrHandler= function(msg, url, linenumber) {
console.log('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
return true;
}

goErrHandler();

so in console you'll see some thing like this :

Error message: undefined
URL: undefined 
Line Number: undefined


回答3:

The better solution is to use try/catch, e.g.

try{
    if(a=='a'){

    }
}catch(e){
    alert(e);
    //or send to server
    new Image().src='errorReport.php?e='+e;
}

Google Plus seems to use this.