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
Chris ShadeChris Shade 

Trouble Catching Error

We have a custom field called Unique Email that is enforced to be unique.  This field is populated by a apex trigger that runs before inserting/updating.  I'm trying to use try/catch to take an alternate action if this error is experienced but the catch doesn't seem to be happening:

User-added image

Here is my code:

trigger uniqueEmail on Contact (before insert, before update) {

        for (Contact c : Trigger.new) {  
            try{
                c.Unique_Email__c = c.Email;
            }
          
            catch(Exception a){
                system.debug(c.id);
                c.Unique_Email__c = NULL;
                List<Contact> contactList = new list<Contact>();
                contactList = [SELECT Id,Email,Remove__c
                                    FROM Contact
                                    WHERE email = :c.Email AND id != :c.id
                                    LIMIT 100];
            
                for(Contact updateContact : contactList)
                {
                    updateContact.Remove__c = FALSE;
                    update updateContact;
                }
                if(c.id==Null){
                    c.Unique_Email__c = NULL;
                    Delete c;
                }
                else{
                    for(Contact cOld : trigger.old){
                        c.Unique_Email__c = NULL;
                    }
                    
                }
                //insert email code
            }
        }
    
}


 
Best Answer chosen by Chris Shade
surasura
you should surround your insert or update statment with try catch . As  c.Unique_Email__c = c.Email; statement wont generate a exception becuase it is a simple assignment operation not a dml operation
if you have a custom controller and you are doing save (insert /update)  via your code use try catch there 

All Answers

Andy BoettcherAndy Boettcher
Welcome to the Apex "Order of Execution"  =)  https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_order_of_execution.htm?SearchType=Stem&Highlight=workflow%7CWorkflow%7Cworkflows%7C%7Crules%7CRules%7CRule%7Crule

The document doesn't say it specifically, but I'm making a good guess that you aren't able to catch the error because the error is happening before your trigger code fires.
surasura
you should surround your insert or update statment with try catch . As  c.Unique_Email__c = c.Email; statement wont generate a exception becuase it is a simple assignment operation not a dml operation
if you have a custom controller and you are doing save (insert /update)  via your code use try catch there 
This was selected as the best answer
Chris ShadeChris Shade
Thank Sura.  That worked.