1

我正在为一个 jQuery 练习项目进行错误处理,我想知道如果发生错误,是否可以获取该行。例如:

function number(x) {
    if (x === 1) {
        alert("ok");
    } else {
        alert("Invalid number was given on line ...")
    }
}

number(2);​

现在我想提醒而不是 ... 发生错误的行。在此先感谢。

4

2 回答 2

0

你可以window.onerror在你的脚本中使用,像这样

window.onerror = function(msg, url, line) {
       alert("Error:"+msg+'at'+url+':'+line);
};
于 2012-11-05T12:16:33.973 回答
0

示例 1:

此示例显示如何捕获异常并显示有关错误的信息:

try {
    unknownFunction ();
}
catch(e) {
document.write ("The error message: <b>" + e.message + "</b>");
if ('number' in e) {
    document.write ("<br />");
    document.write ("The error code: <b>" + e.number + "</b>");
}
if ('lineNumber' in e) {
    document.write ("<br />");
    document.write ("The error occurred at line: <b>" + e.lineNumber + "</b>");
}
}

示例 2:

此示例显示如何创建和捕获自定义异常:

try {
    var err = new Error ();
    err.message = "My first error message";
     if (err.fileName === undefined) { // IE, Opera, Google Chrome and Safari
    err.fileName = document.location.href;
    }
    throw err;
}
catch(e) {
document.write ("The error message: <b>" + e.message + "</b><br />");
document.write ("The error occurred in the following file: <b>" + e.fileName + "</b>");
于 2012-11-05T14:38:08.617 回答