处理Javascript中的运行时错误

Handling Runtime errors in Javascript

本文关键字:运行时错误 Javascript 处理      更新时间:2023-09-26

我想处理Javascript中的运行时错误。但我遇到了一个问题。当我习惯了窗户。onerror函数,我可以得到非异常错误。但我在任何已定义的函数中定义了一个未定义的函数。我看不出有什么例外。我哪里出错了?

这是我使用的代码;

function errorHandler(message, url, line, column, error) {
debugger    
var message = [
'Message: ' + message,
''nURL: ' + url,
''nLine: ' + line,
''nColumn: ' + column,
];

}窗口。onerror = errorHandler;

index . html代码;

function exceptionTest() {
        test();
    }

exceptionTest()函数在我的代码中定义。但测试函数是未定义的。我想要得到一个关于未定义函数的错误。我该怎么做呢?它只显示浏览器的控制台窗口。谢谢你的建议。

您可以使用try catch块来捕获这些错误:

try{
    test();
} catch(error){
   console.log("Following error happened:", error);
}

嗯,我尝试了下面的用例,其中onerror取自此MDN链接

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body onload="Test1();">
    <script type="text/javascript">
        function Test1() {
            Test2();
        }
        window.onerror = function (msg, url, lineNo, columnNo, error) {
            var string = msg.toLowerCase();
            var substring = "script error";
            if (string.indexOf(substring) > -1) {
                alert('Script Error: See Browser Console for Detail');
            } else {
                var message = [
                    'Message: ' + msg,
                    'URL: ' + url,
                    'Line: ' + lineNo,
                    'Column: ' + columnNo,
                    'Error object: ' + JSON.stringify(error)
                ].join(' - ');
                //uncomment below line to see the message in console.
                //console.log(message); 
                alert(message);
            }
            return false;
        };
    </script>
</body>
</html>

并显示正确的消息,错误的位置,行号和列号。

登录到控制台时的错误信息如下:

DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
HTMLPage1.html
HTML1300: Navigation occurred.
HTMLPage1.html
SCRIPT5009: 'Test2' is undefined
HTMLPage1.html (12,13)
Message: 'Test2' is undefined - URL: file:Desktop/HTMLPage1.html - Line: 12 - Column: 13 - Error object: undefined
HTMLPage1.html (29,17)