How to handle trigger/validation error in Lightning Components?

How to handle trigger/validation error in Lightning Components?

Sample Code:


Sample.cmp:

<aura:component implements=”force:appHostable”
                controller=”Sample”>
    
    <div class=”slds-box slds-theme_default”>
        <lightning:button variant=”brand” label=”Click It” onclick=”{!c.clickIt}”/>
    </div>
    
</aura:component>


SampleController.js:


({
    clickIt : function(component, event, helper) {
        var action = component.get(“c.createContact”);
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === “SUCCESS”) {
                alert(“Contact Created successfully”);
            } else if (state === “ERROR”) {
                alert(response.getError()[0].message);
            } else if (state === “INCOMPLETE”) {
                alert(“No response from server or client is offline.”);
            }
        });
        $A.enqueueAction(action);        
    }
})


Sample Apex Class:


public class Sample {

    @auraEnabled
    public static void createContact() {
        try {            
            Contact con = new Contact(FirstName = ‘Test’);
            insert con;
        }
        catch (Exception e) {
            throw new AuraHandledException(‘Something went wrong: ‘ + e.getMessage() + ‘. Contact Your Administrator’);    
        }
        finally {
            
        }        
    }
    
}

Output:

Leave a Reply