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
Travis MalleTravis Malle 

Throw a user friendly error message in apex

I have a class that is called by a before trigger. The class is designed to loop through records and evaluate who it belongs to and the datetime. there are a few things happen with this logic that are outside of this post. I now have a need to present a user friendly error message if there are more than one record with the same owner and same datetime. I am able to successfully throw the error and prevent a save (exactly what I want). However, I would like a more user friendly error message. Here is a snip of how my error is triggered and the resulting message. Any way to clean this up??? Something more akin to validation message
 
else if(officer == prevOfficer && StartDate == prevDate){ 
                // same officer and exact same time (throw error)
                if(initialTime == prevDateTime){
                    throw new CustomException('Cannot have two events start at the same time');
                }
User-added image
 
Raj VakatiRaj Vakati
Use Trigger.addError(' Cannot have two events start at the same time');
Travis MalleTravis Malle
Thank you Raj and Naveen,
When I use the addError method, i get an even more cryptic message. See image below.
else if(officer == prevOfficer && StartDate == prevDate){ 
                // same officer and exact same time (throw error)
                if(initialTime == prevDateTime){
                    e.addError('Cannot have two events start at the same time');
                  //  throw new CustomException('Cannot have two events start at the same time');
                }

User-added image
Travis MalleTravis Malle
It appears that I cannot use AddError outside of a trigger. Also, correction to my original post, this class is called by an after trigger. Does anyone know a workaround for this?

 
Naveen IlaNaveen Ila
Hi Travis, 

Below is one possible solution with Unique field. Which displays user friendly message(However in lightening (https://success.salesforce.com/ideaView?id=0873A000000LmkwQAC), it still having a problem). 

Step1: Create a text field with Unique Type

Unique Field

Step2: Create a workflow rule load this field with following forumula (OwnerId + TEXT( ActivityDateTime )) and click the check box  Re-evaluate Workflow Rules after Field Change

Unique Field


Step3: Activate the Workflow rule. 

If user creates an event from onwords with same start date time they will see an error here

User-added image