1

I am trying to display apex catch exception error message in lightning message. I have tried below in helper. but it didn't work. And let me know how to call this from Lightning component.

Helper:

    saveAction.setCallback(this,function(response){
                    if (response.getState() == "SUCCESS") {
                    component.set("v.isShow",false);
                    var opportunitId = response.getReturnValue();
                    window.location.href = "/"+opportunitId;
                    }
                });
                $A.enqueueAction(saveAction);

Lightning Controller:

    saveRecord : function(component, event, helper)
        {
            helper.helperSave(component, event);
        }
  • 1
    You'll need to implement error handling code in your JavaScript controller or handler (depending on where you fire the action). There are examples in the Lightning component developer guide as a guide. There's also a detailed tutorial on the Salesforce Developer blog. – David Reed Jan 23 at 18:17
5

two things,

In your apex handle the exception like so

try {
    // your code here
}
catch (Exception e //if you know what type of error it is going to throw you can be more specific ie. NullPointerException e) {
    // "Convert" the exception into an AuraHandledException
    throw new AuraHandledException(e.getMessage());    
}

Now you have to handle the error in the javascript controller

  saveAction.setCallback(this,function(response){
      let state = response.getState();          
      if (state == "SUCCESS") {
        component.set("v.isShow",false);
        var opportunitId = response.getReturnValue();
        var navEvt = $A.get("e.force:navigateToSObject");
        navEvt.setParams({
           "recordId": opportunityId
        });
        navEvt.fire();
       } else if(state = "ERROR"){
           errorMsg = response.getError()[0];
           let toastParams = {
             title: "Error",
             message: errorMsg, // Default error message
             type: "error"
            };
           let toastEvent = $A.get("e.force:showToast");
           toastEvent.setParams(toastParams);
           toastEvent.fire();
          }
        });
        $A.enqueueAction(saveAction);
    }

Also use the built in object redirect to navigate to the opportunity.

var navEvt = $A.get("e.force:navigateToSObject");
navEvt.setParams({
  "recordId": opportunityId
});
navEvt.fire();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.