1

I have a web component (lwc) with a child component that makes an imperative server call. When an exception is thrown by the server the parent component is not catching it in the errorCallback. The parent errorCallback is working when the child throws from other parts of the code.

I'm ok to work around this and trigger an event to notify the parent but I wonder if this is expected behaviour?

pseudocode

   /* parent.html */
  <template>
   <c-child></c-child>
  </template>

/* parent.js */
import { LightningElement} from 'lwc';
export default class child extends LightningElement {
  errorCallback(err){
   console.log('parent error handler', err);
 }
}

/* child.html */
<template>
</template>

/* child.js */
import { LightningElement } from 'lwc';
import getDataFromServer from '@salesforce/apex/apexController.getData';

export default class child extends LightningElement {
 serverCall(){
  getDataFromServer()
        .then((data) => {
            // process success
        })
        .catch((error) => {
            console.error(error);
            throw error?.body?.message;
        });
    } 
 }
}

I expected the console output to be 'parent error handler' but what I get is 'uncaught in promise'.

1 Answer 1

2

Yes, this is expected behavior. It's a feature of Promises, not LWC specifically. You have to first somehow "break out" of the Promise before you can throw a catchable exception. Something like the following should work:

  error;
  throwError() {
    setTimeout(() => {
      throw this.error;
    });
  }
  serverCall() {
    getDataFromServer()
      .then((data) => {
        // process success
      })
      .catch((error) => {
        this.error = error;
        this.throwError();
      });
  }

The setTimeout breaks us out of the Promise, and we're free to throw the error. Note, however, that the stack trace will show that the error came from throwError, not the original serverCall, so you might need to store additional information about the problem.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .