[removed] how to display script errors in a popup alert?

前端 未结 5 1875
你的背包
你的背包 2020-12-02 10:02

I want to display script errors in a popup alert instead of showing them in the browser console.

window.onerror = function() {
  var message = /* get error m         


        
相关标签:
5条回答
  • 2020-12-02 10:27
    <script>$(window).on("error", function(evt) {
    
    console.log("jQuery error event:", evt);
    var e = evt.originalEvent; // get the javascript event
    console.log("original event:", e);
    if (e.message) { 
        alert("Error:\n\t" + e.message + "\nLine:\n\t" + e.lineno + "\nFile:\n\t" + e.filename);
    } else {
        alert("Error:\n\t" + e.type + "\nElement:\n\t" + (e.srcElement || e.target));
    }
    });
    </script>
    
    0 讨论(0)
  • 2020-12-02 10:39

    Just in case someone would like to use it with jQuery:

    $(window).on("error", function(evt) {
    
        console.log("jQuery error event:", evt);
        var e = evt.originalEvent; // get the javascript event
        console.log("original event:", e);
        if (e.message) { 
            alert("Error:\n\t" + e.message + "\nLine:\n\t" + e.lineno + "\nFile:\n\t" + e.filename);
        } else {
            alert("Error:\n\t" + e.type + "\nElement:\n\t" + (e.srcElement || e.target));
        }
    });
    
    0 讨论(0)
  • 2020-12-02 10:40

    Check this out: http://www.javascriptkit.com/javatutors/error3.shtml. Looks like signature is function(message, url, linenumber).

    0 讨论(0)
  • 2020-12-02 10:42

    Yes, that is the correct way.

    See the reference here:

    http://www.javascriptkit.com/javatutors/error2.shtml

    And explanation of how to see more details of the error here:

    http://www.javascriptkit.com/javatutors/error3.shtml

    Their example:

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

    If you wish to display a LIST of errors in a single pop-up, it's trickier.

    Since the errors occue 1 by 1, you need to do the following:

    • have window.onerror handler store error details in some array
    • Check that array periodically - either via a timer, or on every N'th call of window.onerror handler, or both.

      When the check happens, process entire array, display contents as desired, and empty out an array

    0 讨论(0)
  • 2020-12-02 10:43

    Have a look at The onerror event of the window object, specifically Getting additional details on an error

    0 讨论(0)
提交回复
热议问题