简体   繁体   中英

Error event listeners not working on web components / custom elements

I'm trying to attach unhandledrejection and error event listeners to a web component. 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. 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. But again, I need it at the element level.

You can use 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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