通过 eventListeners 在 JS 中捕获错误

Catching errors in JS via eventListeners

有没有一种方法可以使用事件监听器在 JS 中处理 ReferenceErrorTypeError 之类的错误?我知道 try .. catch .. 但这不是我要找的。

例如:我正在寻找类似 document.onReferenceError 或类似事件侦听器的方法。

我假设您正在尝试进行全局错误处理。对于错误,您不能真正利用 type 本身,但您可以使用以下方法侦听所有错误:

window.onerror = function(message, source, lineno, colno, error) { ... }

对于特定于元素的错误,您有不同的函数签名("for historical reasons" - 根据文档)

element.onerror = function(event) { ... }

在任何一种情况下,您都应该能够检查 errorevent 类型的 instanceof 检查。

//in case of global level checking
error instanceof ReferenceError //boolean

//in case of element level checking
event.type === <type you're looking for>  //boolean

文档 - https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror