Exception handling

Exception Handling In Lightining Component

In This Post  I will Explain you how one can handle exception in lightining component.

So  Before Going to the code lets  know about Exception

What Is Exception ? 

Exception is an event which occur during execution of  program instruction and disrupts the normal flow of program instructions. Exception handling is a mechanism to handle exception so that normal flow of program should be maintained.

Possible Reason For Exception : 

Sending a request from a Lightning component to an Apex Controller and getting back a response is a path that has several potential failure points.

 

 

Exception handling

 

Steps to followed to  perform Exception Handling Are :

  1. Create the lightning component to show the exception.
<-- errorComponent -->
<aura:component>
    <aura:attribute name="errorMsg" type="String"></aura:attribute>
    <aura:attribute name="title" type="String"></aura:attribute>
    <div class="wk_model_bg"></div>
    <section role="dialog"  aria-labelledby="header" aria-describedby="errMsg" class="slds-modal slds-fade-in-open">
        <div class="slds-modal__container " aura:id="ErrorBox" >
            <div class="slds-modal__header" aura:id ="errHeader">
                <lightning:buttonIcon aura:id="clsBtn" iconName="utility:close" alternativeText="Close" class="slds-button slds-button--neutral slds-p-horizontal--xx-small slds-m-right--x-small slds-float--right" onclick="{!c.myAction}">     
                </lightning:buttonIcon> 
                <h2 id="header" class="slds-text-heading--medium wk_text">{!v.title}</h2>
            </div>
            <div class="myAction slds-p-around--large" aura:id ="errMsg" style="background:#f4f6f9">
                {!v.errorMsg}
            </div>
        </div>
    </section>
     
</aura:component>

2. Create a client site controller for errorComponent.

({
   
    myAction : function(component, event, helper) {
        component.destroy();
    }
})

3.   Code for component that will through an exception . in this component we have a button to          delete Account record but this account can not deleted as it is associated with the case.

<aura:component controller = "accListJsClass">
      <div aura:id="errorDialogPlaceholder" >
        {!v.body}
      </div>
        <div class="slds-col slds-size_1-of-8 allBtn">
            <lightning:button label="Delete Account"
                                     iconName="utility:delete"
                                     iconPosition="left"
                                     variant="destructive"
                                     onclick="{!c.deleteSlctd}">
            </lightning:button>
        </div>
</aura:component>

4 . Create a client site controller for deleteAccount.

({
        deleteSlctd : function(component,event,helper) {
        var getCheckAllId = component.find("cboxRow");
        var selctedRec = [];
        for (var i = 0; i < getCheckAllId.length; i++) {
             
            if(getCheckAllId[i].get("v.value") == true )
            {
                selctedRec.push(getCheckAllId[i].get("v.text")); 
            }
        }
        helper.deleteSelected(component,selctedRec);
    }
})

5. Create a Helper for deleteAccount.

    deleteSelected : function(component,selctedRec){
        var action = component.get("c.delSlctRec");
        action.setParams({
            "slctRec": selctedRec
        });
        action.setCallback(this, function(response){
            var state =  response.getState();
            if(state == "SUCCESS")
            {
                var errorMsg = "Successfully Deleted";
                var error = "Success";
                $A.createComponent(
                    "c:errorComponent",
                    {
                      "errorMsg": errorMsg,
                        "title" : error
                     },
                    function(errComponent){
                        if (component.isValid()) {
                            var targetComp = component.find("errorDialogPlaceholder");
                            var body = component.get("v.body");
                            body.push(errComponent);
                            component.set("v.body", body);             
                        }
                    }            
                );
            } else if (state=="ERROR") {
                var errorMsg = action.getError()[0].message;
                console.log(errorMsg);
                var error = "Error";
                $A.createComponent(
                    "c:errorComponent",
                    {
                      "errorMsg": errorMsg,
                        "title" : error
                     },
                    function(errComponent){
                        if (component.isValid()) {
                            var targetComp = component.find("errorDialogPlaceholder");
                            var body = component.get("v.body");
                            body.push(errComponent);
                            component.set("v.body", body);             
                        }
                    }            
                );
            }
        });
        $A.enqueueAction(action);
    }
})

6 . Create apex class to perform the delete operation.

 
    @AuraEnabled 
    public List<Account> delRec = new List<Account>();
     
    @AuraEnabled 
    public static List<Account> delSlctRec(List<String> slctRec)
    {
        accListJsClass alc = new accListJsClass();
        // Id is for demo purpose only 
        alc.delRec = [SELECT Id FROM Account WHERE Id = '0017F000006PUEaQAO' ]; 
        try{
           delete alc.delRec;
        } catch(Exception ex)
        {
            throw new AuraHandledException(ex.getMessage());
        }
        
    }
}

 

Hits: 299

Share Post

By Himanshu Rana

My Name is Himanshu Rana, 23 Years young, born and grow up in Ghaziabad, India. A High Spirited Salesforce Admin, Developer and a Blogger. I currently work at Wakencode Technologies,

Leave a Reply

Your email address will not be published. Required fields are marked *