function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
scott_devscott_dev 

How to get a validation error message from trigger code to lightning component

I'm trying to receive a message from a validation rule when a custom object record is saved - and then display it in a toast message. The message I am receiving when the validation fails is much more than just the validation message. For example:

User-added image

The validation message is buried in there, but I can't seem to isolate it, and always get everything else with it. I receive the above error when setting the validation rule on a secondary object that is updated by the trigger of the primary object.

In contrast, if I only set the validation rule on the primary object I receive this error that is much nicer and only contains the validation message:

User-added image

I'm wondering if the error message coming back contains all that extra information because it is being called via a trigger? Regardless, I need to understand how to only return the message from the validation rule, without the whole stacktrace and such.

Here is the code in my js controller:

setStageActive: function(component, event) {
    var action = component.get("c.updateStageAsActive");
    action.setCallback(this, function(response) {
      var state = response.getState();

      if (component.isValid() && state === "SUCCESS") {
        // Do everything we want when successful
          this.showToast("success", "dismissible", null, "Stage changed successfully.");
        }
      } else {
        var errors = response.getError();
        var title = "Some errors were encountered when trying to update the Stage";
        var message = "Unknown error."; // Default error message

        if (errors && errors[0].message) {
          message = errors[0].message;
        }
        this.showToast("error", "sticky", title, message);
      }
    });
    $A.enqueueAction(action);
  }
updateStageAsActive method in my Apex controller
  @AuraEnabled
  public static List<Matter_Stage_Activity__c> updateStageAsActive() {
      List<Matter_Stage_Activity__c> matterStageActivityList;

      try {
        matterStageActivityList = matterStageActivityHandler.updateStageAsActive();
      } catch (DmlException e) {
        throw new AuraHandledException(e.getDmlMessage(0));
      } catch (Exception e) {
        throw new AuraHandledException(e.getMessage());
      }
      return matterStageActivityList;
    }
  }
methodCalledByTriggerOfPrimaryObject on save of the primary custom object
private void methodCalledByTriggerOfPrimaryObject () {
   	
    // Code to build secondaryObjectsToUpdate

    try {
	   update secondaryObjectsToUpdate;
	} catch (DmlException e) {
       MyException ex = new MyException(e.getDmlMessage(0));
	   throw ex;
	}
}