[SalesForce] How to handle errors in “e.recordSave” in lightning component

I have a component like this:

<div>
  <force:recordEdit aura:id="edit" recordId="{!v.contactId}" />
</div>
<div>
  <ui:button label="Save" press="{!c.saveEdit}"/>
  <ui:button label="Cancel" press="{!c.cancelEdit}"/>
</div>

I need to know how to handle validation errors in the controller. Since I'm using the force:recordEdit component, I don't know if I can gain access to the required fields and validate that they have a value before trying to save. The other option would be to do some kind of a try/catch on the save method – but I can't find any docs on how to do that exactly with the following code:

saveEdit : function(component, event, helper) {
    var edt = component.find("edit");
    console.log('edt: ',edt);
    edt.get("e.recordSave").fire();
    // Update the component
    helper.getContact(component);
    helper.toggleModal(component);
}

I either need to do some pre-validation on the form so I can assure that there are good values in each field, or I need to do some kind of try{edt.get("e.recordSave").fire();}catch(err){ do something here }

Anyone on here done this already?

Best Answer

You may want to bubble the event to the front end rather than catching it at backend .

Here is a simple patterns that I have been following for lightning components to show error on the page

component

 <aura:attribute name="messages" type="Aura.Component[]" access="GLOBAL"/>

<div aura:id="messages">
    {!v.messages}
</div>

Error handling in controller.js

if (state === "SUCCESS") {

}else if (state === "ERROR") {
   var errors = response.getError();
   if (errors[0] && errors[0].pageErrors) {
        console.log(errors[0].pageErrors);
        $A.createComponents([
            ["ui:message",{
                "title" : "Deletion Failed:",
                "severity" : "error",
            }],
            ["ui:outputText",{
                "value" : errors[0].pageErrors[0].message
            }]
            ],
            function(components) {
                var message = components[0];
                var outputText = components[1];
                // set the body of the ui:message to be the ui:outputText
                message.set("v.body", outputText);
                component.set("v.messages", message);  
                setTimeout(function() {
                $A.run(function() {
                    component.set("v.messages", []);                                       
                });
            }, 10000)
            } )   
        } else {
         $A.error("Unknown error");
        }
       }
   });
   $A.enqueueAction(action);
 }

Also i see one of my colleagues has a simpler way to handle the error .You may want to try that as well

https://balkishankachawa.wordpress.com/2016/01/19/understanding-server-side-errors-in-lightning/