Chapter 26: Error Callback in Lightning Web Component

In this chapter we will learn about errorCallback() in Lightning Web Component.

  • It Captures errors that may happen in all the child components lifecycle hooks
  • This method is unique to LWC
  • It has two parameters error and stack.The error argument is a JavaScript native error object, and the stack argument is a string.
  • Error in parent shows in UI no boundary component for it. This means if there is error in child then parent handles the error but if there is error in parent then it is shown in the UI.
  • This method works like a Javascript catch() block for catching errors

SampleΒ 

errorCallback(error, stack){
        console.log('errorcallback - grandparent' + error );
        console.log(stack);
 }

Example

parent.html

<template>
    I am in parent comonent<br/>
    <c-child> </c-child>

</template>

parent.js

import { LightningElement } from 'lwc';

export default class App extends LightningElement {

    errorCallback(error, stack){
        console.log('errorcallback -parent' + error );
        console.log(stack);
    }
}

child.html

<template>
    I am in child component
</template>

child.js

import { LightningElement} from 'lwc';

export default class App extends LightningElement {

    constructor(){
        super();
        console.log('constructor - child');
        throw 'woops error'
    }
    
    errorCallback(error, stack){
        console.log('errorcallback - child' + error );
        console.log(stack);
    }
}

Console Output

In the console we can see that error is handled by the parent component because of errorCallback() in the parent component.

If we did not added errorCallback() in parent component then we have seen below output

Also, note that child component error is handled by parent but parent component errors will be seen in the UI.

Reference

Handle Component Errors

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes