如何用 "onerror" 捕获 "ReferenceError"

How to catch an "ReferenceError" with "onerror"

我希望我的脚本检查许多依赖项,成功后应该会出现一个提交按钮。但是,如果出现任何类型的 javascript 错误,则该按钮永远不会出现。所以我想在我的脚本末尾做类似的事情:

if (typeof window.error_has_appeared == 'undefined') {
    button.classList.add("button_activated");
}

我已尝试使用 window.onerror 解决我的问题,但它似乎无法捕获所有错误。

<script type="text/javascript">
window.onerror = function(msg, url, line, col, error) {
   alert("ERROR");
};

window.onload = async function() {
   test
};
</script>

我可以在 javascript 日志中看到:"ReferenceError: test is not defined"。但为什么 onerror 警报不起作用?

因为您已将 onload 处理程序设为 async 函数,所以 ReferenceError 不是由全局错误处理程序处理的未处理错误,而是未处理的承诺拒绝,因此它是由全局承诺拒绝处理程序处理。

由于 load 事件代码不对异步函数返回的承诺做任何事情,只需让您的函数不 async:

window.onerror = function(msg, url, line, col, error) {
   console.log("ERROR");
};

window.onload = function() {
   test
};

或使用onunhandledrejection:

window.onerror = function(msg, url, line, col, error) {
   console.log("onerror triggered");
};
window.onunhandledrejection = function(msg, url, line, col, error) {
   console.log("onunhandledrejection triggered");
};

window.onload = async function() {
   test
};