error
2025年01月07日
一、认识
error 当资源加载失败或无法使用时,会在 Window
对象触发 error
事件。例如: script
执行时报错。
二、语法
window.addEventListener("error", function(){})
window.onerror = function (){}
三、操作
3.1 阻止默认事件
window.onerror
: 通过 return true
来阻止默认事件
window.addEventListener
: 通过 e.preventDefault()
来阻止默认事件
四、场景
4.1 window.onerror
window.onerror
异常捕获
- Html
- Css
- JavaScript
<script>
window.onerror = function (e) {
console.log(e);
return true;
};
</script>
<script>
console.log(a);
</script>
4.2 window.addEventListener
window.addEventListener('error')
异常捕获
- Html
- Css
- JavaScript
<script>
const errorMap = {
jsRun: "js 运行时错误",
img: "img 资源加载失败",
link: "link 资源加载失败",
script: "script 资源加载失败",
};
function handlerError(e) {
e.preventDefault();
const { colno, error, filename, lineno, message, srcElement, target } =
e;
const currentTarget = srcElement || target;
let errorType;
if (currentTarget instanceof HTMLScriptElement) {
errorType = "script";
} else if (currentTarget instanceof HTMLLinkElement) {
errorType = "link";
} else if (currentTarget instanceof HTMLImageElement) {
errorType = "img";
} else {
errorType = "jsRun";
}
console.log(errorMap[errorType], errorType === "jsRun" ? message : "");
}
window.addEventListener("error", handlerError, true);
</script>
<link href="https://test.cn/×××.css" rel="stylesheet" />
<script src="https://test.cn/×××.js"></script>
<img src="https://test.cn/×××.jpg" />
<script>
[3, 4].forEach((item) => {
console.log(item.a.b);
});
console.log(a);
setTimeout(() => {
console.log(b);
}, 300);
</script>