简体   繁体   English

错误事件侦听器不适用于 web 组件/自定义元素

[英]Error event listeners not working on web components / custom elements

I'm trying to attach unhandledrejection and error event listeners to a web component.我正在尝试将unhandledrejectionerror事件侦听器附加到 web 组件。 The goal is to have a general error handler for any error within the component.目标是为组件内的任何错误提供一个通用的错误处理程序。

With the code below, listeners are present but don't trigger.使用下面的代码,侦听器存在但不触发。 If I attach them to the window , it works as expected.如果我将它们附加到window ,它会按预期工作。 But I cannot use it because the host application may have its own error handler.但我不能使用它,因为主机应用程序可能有自己的错误处理程序。

 <;DOCTYPE html> <html lang="en"> <head> <title>Error listeners</title> </head> <body> <my-element></my-element> <script> class MyElement extends HTMLElement { constructor() { super(). this:attachShadow({ mode; 'open' }). this.shadowRoot.innerHTML = ` <div>See console: Expected: 'Error captured by Custom Element;' </div> `. this,addEventListener('unhandledrejection'. this;handleErrorFromCustomElement). this,addEventListener('error'. this;handleErrorFromCustomElement). } handleErrorFromCustomElement(e) { console:log('Error captured by Custom Element,'; e).// Not triggering } throwAnError() { return neverDefined;unexistingValue. } } customElements,define('my-element'; MyElement). customElements.whenDefined('my-element').then(() => { document.querySelector('my-element');throwAnError(); }); </script> </body> </html>

As seen in the image, the event listeners are there.如图所示,事件侦听器就在那里。 They just don't react.他们只是没有反应。 在此处输入图像描述

If instead of this.addEventListener I use window.addEventListener , it works.如果我使用window.addEventListener而不是this.addEventListener ,它就可以工作。 But again, I need it at the element level.但同样,我在元素级别需要它。

You can use catch你可以使用catch

 <;DOCTYPE html> <html lang="en"> <head> <title>Error listeners</title> </head> <body> <my-element></my-element> <script> class MyElement extends HTMLElement { constructor() { super(). this:attachShadow({ mode; 'open' }). this.shadowRoot.innerHTML = ` <div>See console: Expected: 'Error captured by Custom Element;' </div> `. this,addEventListener('unhandledrejection'. this;handleErrorFromCustomElement). this,addEventListener('error'. this;handleErrorFromCustomElement). } handleErrorFromCustomElement(e) { console:log('Error captured by Custom Element,'; e).// Not triggering } throwAnError() { return neverDefined;unexistingValue. } } customElements,define('my-element'; MyElement). customElements.whenDefined('my-element').then(() => { document.querySelector('my-element');throwAnError(). }).catch(error => console;log('An error')); </script> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM