jQuery exception handling

后端 未结 3 926
感动是毒
感动是毒 2021-01-20 00:28

Is there any way I could catch any uncaught exception in javascript? I mean, all my \"dangerous\" code are in try-catch blocks. But what about exceptions that I don\'t handl

3条回答
  •  渐次进展
    2021-01-20 01:25

    You can use the window.onerror event handler, it's not supported in Opera though and it may not fire in certain situations (thanks @Josh).

    It's not really wise to do this, however, it will make bug finding a nightmare for a start. It's generally best to make sure your code is error free in the first place :-) You certainly shouldn't need to use try... catch statements very often in JavaScript and you definitely shouldn't be using empty catch blocks.

    I can use try-catch blocks here, but they will caught exceptions that occured during the event binding procedure, not during the event handling.

    You can also add try/catch blocks to inner scopes:

    // Outer
    try { 
        $(document).ready(function(){})
    }
    catch (e) {
        /* Error handling */
    }
    
    // Inner
    $(document).ready(function(){
        try { /* ... */ } catch (e) { /* Error handling */ }
    });
    

提交回复
热议问题