3

I am trying to dispatch errors up from a child component to its parent. However, when my code looks like the below, I get two errors.

Code:

dispatch(error) {
    this.dispatchEvent(new CustomEvent("error", {
        detail: error,
        bubbles: true
    }));
}

Errors:

  • Uncaught Error in $A.getCallback() [a.indexOf is not a function]
  • [NoErrorObjectAvailable] [object CustomEvent]

The stack traces don't seem that useful, but I can edit them in if anyone thinks they would help.


If I simply change the type of the CustomEvent from "error" to "demo", both errors go away. I have removed the onerror listener on the parent component just to reduce the number of variables, so either way the event is ignored (at present). Previously, I had:

<c-child-component onerror={handleError}>
</c-child-component>

Note that I have read through Create and Dispatch Events, but it does not make any mention of any preclusion related to standard names of event types.

The CustomEvent() constructor has one required parameter, which is a string indicating the event type. As a component author, you name the event type when you create the event. You can use any string as your event type. However, we recommend that you conform with the DOM event standard.

  • No uppercase letters
  • No spaces
  • Use underscores to separate words

Don’t prefix your event name with the string on, because inline event handler names must start with the string on. If your event is called onmessage, the markup would be <c-my-component ononmessage={handleMessage}>. Notice the doubled word onon, which is confusing.

1 Answer 1

5

onerror is a standard DOM event. It's raised by elements that can load data, such as img elements, if the requested resource fails to load. You should avoid using the name of any standard DOM event in both Aura and LWC when firing off custom events. That said, if you want to fire off a standard event, you can:

this.dispatchEvent(
  new ErrorEvent('error', { 
    message: errorMessage 
  }
))

Demo.

Note that message must be a string, so if you want to pass an object, you need to transform it to a string first, such as with JSON.stringify, then parse it in the event handler, such as JSON.parse.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.