How to use errorCallback

LWC have dedicated errorCallback lifecycle hook, which can catch any uncaught errors from descendent components in its tree!

How to use errorCallback

LWC have dedicated errorCallback lifecycle hook, which can catch any uncaught errors from descendent components in its tree!

javascript
import { LightningElement } from 'lwc';

export default class ErrorCallback extends LightningElement {
    errorCallback(error) {

    }
}

Let’s create two components: JavascriptError and ForcedError and simulate some errors.

javascript
import { LightningElement } from 'lwc';

export default class JavascriptError extends LightningElement {
    connectedCallback() {
        throw new Error('Javascript error!');
    }
}
javascript
import { LightningElement } from 'lwc';

export default class ForcedError extends LightningElement {
    handleClick() {
        throw new Error('Forced error!');
    }
}

Both our components are inside of ErrorCallback component. We’re gonna print our errors with console.error.

javascript
import { LightningElement } from 'lwc';

export default class ErrorCallback extends LightningElement {
    errorCallback(error, stack) {
        console.error(error.message);
        console.error(stack);
    }
}

Our first error came from connectedCallback in JavascriptError component - you can see its name in stack part.

Don't do this
How to use errorCallback — screenshot 3

Second error appeared after button click - which triggered handleClick function.

It’s worth to mention that errorCallback won’t catch an error thrown during asynchronous operations like promises or timeouts - those types of errors you’ll have to handle on your own!

Text and code were extracted from the original slide. Plain-text version of the whole catalog