我正在为jQuery练习项目进行错误处理,我想知道是否有可能让错误发生。例如:
function number(x) {
if (x === 1) {
alert("ok");
} else {
alert("Invalid number was given on line ...")
}
}
number(2);
现在我想提醒而不是......发生错误的行。提前致谢。
答案 0 :(得分:0)
您可以在脚本中使用 window.onerror
,例如
window.onerror = function(msg, url, line) {
alert("Error:"+msg+'at'+url+':'+line);
};
答案 1 :(得分: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>");