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
jonpilarski1.3914448382645588E12jonpilarski1.3914448382645588E12 

How to catch DML Exception in APEX trigger

Hi Everyone

I have a simple before update trigger below. I am trying to catch any error and log to a custom table. The below will cause Duplicate error in UI but nothing is inserted into custome object USD_Error_Log__c.. Its like trigger does not fall into either DMLException or Exception catch blocks. Any and all help is appreciated.

Thanks

Jon

trigger USD_Contact on Contact(before update){

Set<USD_Error_Log__c> student = new Set<USD_Error_Log__c>(); 

for (Contact c: Trigger.new) {
    // delete [select id from USD_Error_Log__c];    
    
try{
  
     c.TargetX_SRMb__BannerID__c = '008372883';   // this will cause Duplicate value on record error      
     
} catch (DMLException e) {

  string error = e.getMessage();
  student.add(new USD_Error_Log__c(Banner_ID__c = c.TargetX_SRMb__BannerID__c,Error_Message__c = error ));
  
  if(!student.isEmpty()){   
   List<USD_Error_Log__c> toInsert = new List<USD_Error_Log__c>();
   try{
      toInsert.addAll(student);
      insert toInsert;     
   }catch(Exception se){
   }                             
  } 

} catch(Exception e) {
    
  string error = e.getMessage();
  student.add(new USD_Error_Log__c(Banner_ID__c = c.TargetX_SRMb__BannerID__c,Error_Message__c = error ));
  
  if(!student.isEmpty()){   
   List<USD_Error_Log__c> toInsert = new List<USD_Error_Log__c>();
   try{
      toInsert.addAll(student);
      insert toInsert;     
   }catch(Exception se){
   }                             
  } 
  
    
}

}//end loop



}
Amit Chaudhary 8Amit Chaudhary 8
Bulk DML Exception Handling
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dml_bulk_exceptions.htm

An Introduction to Exception Handling
https://developer.salesforce.com/page/An_Introduction_to_Exception_Handling
Please try dataBase.insert or update like below code.
Database.SaveResult[] lsr = Database.update(accounts, false); 

for(Database.SaveResult sr : lsr){ 
    if (!sr.isSuccess()) { 
        myMethodToaddToErrorObjectList(sr);
    }
}
// Create the list of sObjects to insert
List<Account> acctList = new List<Account>();
acctList.add(new Account(Name='Acme1'));
acctList.add(new Account(Name='Acme2'));

// DML statement
Database.SaveResult[] sr = Database.insert(acctList, false);

// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted account. Account ID: ' + sr.getId());
    }
    else {
        // Operation failed, so get all errors                
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Account fields that affected this error: ' + err.getFields());
        }
    }
}
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_database.htm

Please modify your code according to above code.

Let us know if that will help u

Thanks
Amit Chaudhary
Jade ManapeeJade Manapee
it doesnt works. I tried this code
trigger createCor on TestGenCor__c (before insert) {
	GenCOR test = new GenCOR();
	List<TestGenCor__c> listA = new List<TestGenCor__c>();
	for(TestGenCor__c a : Trigger.New) {
        	listA.add(a); 
    }
    // DML statement
	Database.SaveResult[] srList = Database.insert(listA, false);

	// Iterate through each returned result
	for (Database.SaveResult sr : srList) {
    	if (sr.isSuccess()) {
        	// Operation was successful, so get the ID of the record that was processed
        	System.debug('Successfully inserted account. Account ID: ' + sr.getId());
    	}
    	else {
        	// Operation failed, so get all errors                
        	for(Database.Error err : sr.getErrors()) {
            	System.debug('The following error has occurred.');                    
            	System.debug(err.getStatusCode() + ': ' + err.getMessage());
            	System.debug('Account fields that affected this error: ' + err.getFields());
        	}
    	}
	}
}

when i run this
TestGenCor__c c = new TestGenCor__c(Name='Test2', Record_Type__c='waive',Department__c='agency');
insert c;


I got this error
Line: 6, Column: 1
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, createCor: execution of BeforeInsert caused by: System.SObjectException: DML statement cannot operate on trigger.new or trigger.old Trigger.createCor: line 8, column 1: []
Harold CrouseHarold Crouse
I'm not sure if you've figured this out yet.   But you are in a before trigger, you can not do an update on the same records you are currently saving.  If this is just an example you are testing, change the trigger to an after insert.  If you are setting fields in your current records in the before trigger then there is no need to update.  Just set the values and let the code continue.  
Jade ManapeeJade Manapee
I write the following code and it work fine, but not sure if it's s best practice tho.
trigger createCor on TestGenCor__c (before insert) {
	GenCOR test = new GenCOR();
	String result;
	List<TestGenCor__c> existing = new  List<TestGenCor__c>();
	for(TestGenCor__c a : Trigger.new){
		do{
		result = test.GenCOR_addNewType(a.Record_Type__c,a.Department__c);
		existing = ([Select Gen_id__c From TestGenCor__c where Gen_id__c=:result]);
		}
		while(existing.size()>0);
		a.Gen_id__c = result;
	}
}

i need to check if gen a new id until it's not duplicate, that why i use do while.
Sumit Saini 1Sumit Saini 1
Hi Friends,

We can get only dml exception from parent exception.
Please follow the below link for reference.
https://sfdctechsolutions.blogspot.com/2021/07/show-only-dml-exception-message-from.html