JavaScript global event mechanism

前端 未结 10 2175
无人及你
无人及你 2020-11-22 14:39

I would like to catch every undefined function error thrown. Is there a global error handling facility in JavaScript? The use case is catching function calls from flash that

10条回答
  •  悲&欢浪女
    2020-11-22 15:15

    How to Catch Unhandled Javascript Errors

    Assign the window.onerror event to an event handler like:

    
    

    As commented in the code, if the return value of window.onerror is true then the browser should suppress showing an alert dialog.

    When does the window.onerror Event Fire?

    In a nutshell, the event is raised when either 1.) there is an uncaught exception or 2.) a compile time error occurs.

    uncaught exceptions

    • throw "some messages"
    • call_something_undefined();
    • cross_origin_iframe.contentWindow.document;, a security exception

    compile error

    • setTimeout("{", 10);, it will attempt to compile the first argument as a script

    Browsers supporting window.onerror

    • Chrome 13+
    • Firefox 6.0+
    • Internet Explorer 5.5+
    • Opera 11.60+
    • Safari 5.1+

    Screenshot:

    Example of the onerror code above in action after adding this to a test page:

    
    

    Javascript alert showing error information detailed by the window.onerror event

    Example for AJAX error reporting

    var error_data = {
        url: document.location.href,
    };
    
    if(error != null) {
        error_data['name'] = error.name; // e.g. ReferenceError
        error_data['message'] = error.line;
        error_data['stack'] = error.stack;
    } else {
        error_data['msg'] = msg;
        error_data['filename'] = filename;
        error_data['line'] = line;
        error_data['col'] = col;
    }
    
    var xhr = new XMLHttpRequest();
    
    xhr.open('POST', '/ajax/log_javascript_error');
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onload = function() {
        if (xhr.status === 200) {
            console.log('JS error logged');
        } else if (xhr.status !== 200) {
            console.error('Failed to log JS error.');
            console.error(xhr);
            console.error(xhr.status);
            console.error(xhr.responseText);
        }
    };
    xhr.send(JSON.stringify(error_data));
    

    JSFiddle:

    https://jsfiddle.net/nzfvm44d/

    References:

    • Mozilla Developer Network :: window.onerror
    • MSDN :: Handling and Avoiding Web Page Errors Part 2: Run-Time Errors
    • Back to Basics – JavaScript onerror Event
    • DEV.OPERA :: Better error handling with window.onerror
    • Window onError Event
    • Using the onerror event to suppress JavaScript errors
    • SO :: window.onerror not firing in Firefox

提交回复
热议问题