Lit-element: handle component error

Created on 9 Apr 2020  路  3Comments  路  Source: Polymer/lit-element

How handle JS errors from LitElement component's such as lwc feature's ?

I tried to handle errors with window.onerror and on my webcomponent

<my-content @error=${MyView._trackError}> content... </my-content>

  private static _trackError(err): void {
    console.log('SIMULATE TRACK ERROR', err);
  }

It doesn't work. I need this to log my application

Most helpful comment

@sorvell We could potentially offer a mixin that listens for error events and provides an error property that templates can use.

All 3 comments

We don't plan to add this type of feature to LitElement and it's not directly supported in the platform, but you could implement something like this yourself.

You'd need to wrap over all of the lifecycle of the element and try/catch the code, firing an event if there's an exception, for example, constructor, connected/disconnectedCallback, and probably performUpdate.

To get a sense of what you'd do in performUpdate, something like:

performUpdate() {
  try {
    super.performUpdate();
  } catch(err) {
    this.dispatchEvent(new CustomEvent('error', {detail: err});
  }
}

You could even make a class decorator that emits a subclass of the given class that wraps these call sites.

@sorvell We could potentially offer a mixin that listens for error events and provides an error property that templates can use.

Ok, thank's a lot, it's working fine.
I created a trackError decorator.

export const trackError = (descriptor: Constructor<HTMLElement> | ClassDescriptor): any => {
  const { kind, elements } = <ClassDescriptor>descriptor;
  return {
    kind,
    elements,
    // This callback is called once the class is otherwise fully defined
    finisher(clazz: Constructor<HTMLElement>): void {
      const { performUpdate } = clazz.prototype;
      // And all functions needed

      clazz.prototype.performUpdate = function(): void {
        try {
          performUpdate.call(this);
        } catch (err) {
          this.dispatchEvent(new CustomEvent('error', {detail: err});
        }
      };

      // And all functions needed
    },
  };
};

@trackError
@customElement('my-component')
export default class MyComponent extends LitElement { ... }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  3Comments

aadamsx picture aadamsx  路  3Comments

antonioaltamura picture antonioaltamura  路  4Comments

minht11 picture minht11  路  4Comments

sorvell picture sorvell  路  3Comments