一、前言
我们在开发中经常用到try catch来捕获接口错误,并上报到监控平台。这是你是否产生过疑问,这些错误在前端都是如何捕获到的?
二、常见错误类型
- 解析时候发生语法错误
- 值不是所期待类型
- 引用为声明变量
- 资源加载错误
- Http请求错误
三、捕获错误
try catch
能够捕获常规运行时错误,语法错误或异步错误不行
// 常规运行时错误,可以捕获 ✅
try {
console.log(notdefined);
} catch(e) {
console.log( 捕获到异常: , e);
}
// 语法错误,不能捕获 ❌
try {
const notdefined,
} catch(e) {
console.log( 捕获到异常: , e);
}
// 异步错误,不能捕获 ❌
try {
setTimeout(() => {
console.log(notdefined);
}, 0)
} catch(e) {
console.log( 捕获到异常: ,e);
}
window.onerror
window.onerror,当 JS 运行时错误发生时,window 会触发一个 ErrorEvent 接口的 error 事件。
- 监听错误
/**
* @param {String} message 错误信息
* @param {String} source 出错文件
* @param {Number} lineno 行号
* @param {Number} colno 列号
* @param {Object} error Error对象
*/
window.onerror = function(message, source, lineno, colno, error) {
console.log( 捕获到异常: , {
message, source, lineno, colno, error});
}
- 捕获错误情况
// 常规运行时错误,可以捕获 ✅
window.onerror = function(message, source, lineno, colno, error) {
console.log( 捕获到异常: ,{
message, source, lineno, colno, error});
}
console.log(notdefined);
// 语法错误,不能捕获 ❌
window.onerror = function(message, source, lineno, colno, error