+ Start a Discussion
santoshk.behera1.3878016627537622E12santoshk.behera1.3878016627537622E12 

handling DML exception while writing a Trigger

I have created custom object.when error will generate ,it has to logged into the custom object with excsption message and record Id. kindly help me.

trigger  countNoOfContact on Contact (after insert,after update,after delete,after undelete) {
  
HandllingError__c errObj=new HandllingError__c();
    try
    {  
Set<ID> setAccId=new Set<ID>();
   
    if((trigger.IsInsert)||(trigger.IsUndelete)||(trigger.IsUpdate))
    {
  for(Contact con1:trigger.new)
        {   
   if(con1.AccountId!=null)
            {
                setAccId.add(con1.AccountId);
            }
       } 
    }
   
    if((trigger.IsDelete)||(trigger.IsUpdate))
    {       
  for(Contact con1:trigger.new)   // error will generate here, delete operation deals with trigger.old. Problem is :erroris not logged into object.
        {   
   if(con1.AccountId!=null)
            {
    setAccId.add(con1.AccountId);
            }
       }    
    }
   
Map<ID,Account> mapToAccount=new Map<ID,Account>([select id,No_Of_Contacts__c,(select id from Contacts) from Account where id in:setAccId ]);
   
    for(ID accId:mapToAccount.keySet())
    {
        Account acc=mapToAccount.get(accId);
  acc.No_Of_Contacts__c=acc.Contacts.size();
    }    
   
    update mapToAccount.values();
}

catch(DMLException excp)
{
        errObj.Exception_Message__c=excp.getMessage();
        errObj.Line_Number__c=excp.getLineNumber();
        //errObj.Name=excp.getTypeName();
        insert errObj;
    }
}
piyush parmarpiyush parmar
Hi,

Trigger.new is only available for the insert and update triggers, and the records can only be modified in before triggers.

For the Trigger.IsDelete use Trigger.old


Piyush
santoshk.behera1.3878016627537622E12santoshk.behera1.3878016627537622E12
that I know ,I want to handle error........which is not working in this code though I have used DmlException in catch Block and created the custom object for logging the messages,line number of error into that custom object.
Venkat PolisettiVenkat Polisetti
It looks like you just want to catch any Exception and store the exception value in a custom object ( for reasons beyond my comprehension, anyways). You need to catch the general exception rather than the specific DMLExcepiton. Accessing invalid variable is not DMLException. Change your catch statement to:

catch(Exception excp)

Lets us know if that worked.
Thanks,
Venkat