错误处理与调试
错误处理
语句
try/catch 语句
// try 块代码出错, 代码退出执行, 跳转至 catch 块
// 块接受一个对象包含错误信息
try {
window.someNonexistentFunction();
} catch (error) {
console.log(error.message);
} finally {
console.log("finally");
}
finally 子句
// 无论执行 try 块还是 catch 块, 最后都要执行 finally 块
// 只要包含 finally, try/catch 中的 return 失效
try {
return 2;
} catch (error) {
return 1;
} finally {
return 0;
}
错误类型
错误类型
- Error:基类型;
- InternalError:js 引擎报错;
- EvalError:eval() 报错;
- RangeError:越界报错;
- ReferenceError:找不到引用报错;
- SyntaxError:eval() 中使用错误语法报错;
- TypeError:变量不是预期类型报错;
- URIError:encodeURI() 或 decodeURI() 报错;
确定错误类型
// 使用 instanceof 操作符
try {
someFunction();
} catch (error) {
if (error instanceof TypeError) {
// 处理类型错误
} else if (error instanceof ReferenceError) {
// 处理引用错误
} else {
// 处理所有其他类型的错误
}
}
抛出错误
// 值类型不限
throw 12345;
// 内置错误类型
throw new Error("Something bad happened.");
throw new SyntaxError("I don't like your syntax.");
throw new InternalError("I can't do that, Dave.");
throw new TypeError("What type of variable do you take me for?");
throw new RangeError("Sorry, you just don't have the range.");
throw new EvalError("That doesn't evaluate.");
throw new URIError("Uri, is that you?");
throw new ReferenceError("You didn't cite your references properly.");
error 事件
触发时机
- 没有被 try/catch 处理的错误;
参数
// 只能使用 DOM0 写法
// 三个删除依次为错误信息, 错误所在 URL, 行号
// 最后一道防线, 最好不要用到
window.onerror = (message, url, line) => {
console.log(message);
};
调试技术
桌面控制台
快捷键
F12
;
记录到控制台
console.log("log"); // 常规信息
console.error("log"); // 错误信息
console.info("log"); // 通知信息
console.warn("log"); // 警告信息
使用 JS 调试器
// 使用 debugger 关键字, 尽可能使用浏览器存在的调试功能
// 若浏览器支持打断点, 可手动打断点;
function pauseExecution() {
console.log("Will print before breakpoint");
debugger;
console.log("Will not print until breakpoint continues");
}
抛出错误
// 错误信息具有描述性
function assert(condition, message) {
if (!condition) {
throw new Error(message);
} else;
}