Handle Trigger and Validation Rule Error in Lightning Component

Sometimes we can have a requirement to display validation rule error or apex trigger error messages, on save of record in Lightning Component. We can handle those errors from apex controller and can throw messages to Lightning Component. In lightning response object though the state value comes as ERROR but the message in the error object always says ‘Internal Server Error”. Here is an example to handle the Trigger and Validation Rule Error in apex controller to show error messages in Lightning Component.

In below example I’ve used Lead object FirstName, LastName, Email & Company Field in lightning component to create record. And I’ve created a validation rule and a trigger validation on Lead object.

1. Validation rule for Company field (Company cannot be Test Company).

2. In below Trigger I’m checking if FirstName field value is “Test” then it will throw error.

trigger LeadTrigger on Lead (before insert, before update) {
    
    for(Lead obj :Trigger.new){
        if(obj.FirstName == 'Test'){
            obj.FirstName.addError('First name cannot be test');
        }
    }
}

Apex Controller:

public class SampleAuraController {
    
    @AuraEnabled
    Public static void createLead(Lead objLead){
        String msg = '';
        try{
            //Insert Lead Record
            insert objLead; 
            
        }catch(DmlException e){
            //Any type of Validation Rule error message, Required field missing error message, Trigger error message etc..
            //we can get from DmlException
            
            //Get All DML Messages
            for (Integer i = 0; i < e.getNumDml(); i++) {
                //Get Validation Rule & Trigger Error Messages
                msg =+ e.getDmlMessage(i) +  '\n' ;
            }
            //throw DML exception message
            throw new AuraHandledException(msg);
            
        }catch(Exception e){
            //throw all other exception message
            throw new AuraHandledException(e.getMessage());
        }
        finally {
        }
    } 
}

Lightning Component:

<!--Sample.cmp--> 
<aura:component controller="SampleAuraController" implements="flexipage:availableForAllPageTypes,force:appHostable">
    
    <!--Declare Attributes-->
    <aura:attribute name="isSpinner" type="boolean" default="false"/>
    <aura:attribute name="objLead" type="Lead" default="{'sobjectType':'Lead', 
                                                        'FirstName': '',
                                                        'LastName': '',
                                                        'Email': '', 
                                                        'Company': ''}"/>
    
    
    <!--Component Start--> 
    <div class="slds-m-around--xx-large">
        <div class="container-fluid">
            <div class="form-group">
                <lightning:input name="fname" type="text" maxlength="50" required="true" label="First Name" value="{!v.objLead.FirstName}" />
            </div>
            <div class="form-group">
                <lightning:input name="lname" type="text" maxlength="50" required="true" label="Last Name" value="{!v.objLead.LastName}" />
            </div>
            <div class="form-group">
                <lightning:input name="emailId" type="email" maxlength="100" required="true" label="Email" value="{!v.objLead.Email}" />
            </div>
            <div class="form-group">
                <lightning:input name="company" type="text" maxlength="50" required="true" label="Company" value="{!v.objLead.Company}" />
            </div>
        </div>
        <br/>
        <lightning:button variant="brand" label="Submit" onclick="{!c.handleLeadSave}" />        
        <lightning:button label="Cancel" onclick="{!c.handleCancel}"/>        
    </div>
    <!--Component End-->
</aura:component>

Lightning JS Controller:

({    
    //Handle Lead Save
    handleLeadSave : function(component, event, helper) {
        var objLead = component.get("v.objLead");
        var action = component.get("c.createLead");
        action.setParams({
            objLead : objLead
        });
        action.setCallback(this,function(a){
            var state = a.getState();
            if(state === "SUCCESS"){
                alert('Record is Created Successfully');
            } else if(state === "ERROR"){
                var errors = action.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        alert(errors[0].message);
                    }
                }
            }else if (status === "INCOMPLETE") {
                alert('No response from server or client is offline.');
            }
        });       
        $A.enqueueAction(action);
    }
})

Output:

Trigger Error Message:

Validation Rule Error Message:

  • Jayoti Chatterji

    https://uploads.disquscdn.com/images/9f9aef5aaa1d1ef2f61addfb77e545cf5c14a87783d043b2aed21545f6e399d7.png Dear Biswajit, as I execute this in my aura component and try to show the error msg, it seems to give the whole error msg with row and line number, below is the screenshot.

    how can I only extarct the error msg here?

    • Dear Jayoti,
      You can get the trigger and validation rule error message in catch DML exception.

      • Jayoti Chatterji

        I have implemented the same but then also it shows the same error , see the below code reference:

        String msg = ”;
        try{
        voyageRecord.Id = voyageId;
        voyageRecord.recordTypeId = recordTypeId;
        if(recordTypeName != SHL_CommonConstants.Voyage_Internal)
        {
        voyageRecord.SHL_Cargo_Number__c = Null;
        voyageRecord.SHL_Sales_Tag__c = Null;
        List linkingList = [SELECT Id from SHL_Cargo_Linking__c where SHL_Voyage__c=:voyageId];
        if(!linkingList.isEmpty())
        {
        delete linkingList;
        }
        }
        system.debug(‘voyageRecord@@@@@@@’+voyageRecord);
        update voyageRecord;
        }catch(DMLException e){
        system.debug(‘Exception’+e.getMessage());
        for (Integer i = 0; i < e.getNumDml(); i++) {
        //Get Validation Rule & Trigger Error Messages
        msg =+ e.getDmlMessage(i) + 'n' ;
        }
        system.debug('msg'+msg);
        throw new AuraHandledException(msg);

        }

  • Dhana

    The DML exception captures only the 1st validation error. How can that be handled to show all the errors

    • You can get all the errors into a list and show on your screen.

  • kirubakaran viswanathan

    Can’t I combine both the validations in single alert page?

  • kavya reddy

    This is not working. Am getting script-thrown exception in the debug logs.