[SalesForce] Apex Class to Handle Flow/Process Errors from Validation Rules (Invocable Method/Variables)

I'm working on converting our workflow rules to Processes and Flows so that they can be better consolidated and followed by the business. I am running into the "Unhandled Error" message due to validation rules that are in place. So, I'd like to determine the "errors" in my flows, and then pass the information into an apex class that will display the message that I use in my validation rules.

I feel as though I am close, but I'm unsure of how to access the invocable variables within the invocable method. I get an error message on the last line of code when compiling, and am not sure how to accomplish my desired result. I am pretty new to apex, so any guidance would be much appreciated. Code and error message below.

Apex Class

public class OpportunityErrorHandling{

     // Get variables from flow/process
     public class varList {
         @InvocableVariable(label='Error Message' required=true)
         public String errorMessage;
         @InvocableVariable(label='Opportunity' required=true)
         public Opportunity opp;
     }

     // Add error
     @InvocableMethod(
         label='Adds an error to the record'
         description='Will display an error message to the page instead of the unhandled exception error')
     public static void addErrorMessage(List<varList> variables) {
         // Present error message to user
         variables.opp.addError(variables.errorMessage);
     }
 }

Error Message

Error: Compile Error: Initial term of field expression must be a
concrete SObject: List at line 17
column 9

Thank you,

Justin

Best Answer

It's receiving a list, so you have to iterate over the variable list:

for(VarList variable: variables) {
    variable.opp.addError(variables.errorMessage);
}

You shouldn't assume that the list will only have a size of 1, so it's important to iterate over all of them.

Related Topic