Loading

Transaction control in Apex Class and Trigger with Exception Handling

Date de publication: Oct 13, 2022
Description
If DML is initiated from the Apex class which is designed with exception handling, as part of execution it enters into the Trigger. If there is any exception, then control will not come back to the catch block of Apex class. This is expected. 

Below are the sample trigger and Apex class which explains the behavior:
trigger TheTrigger on Account (before insert, after insert)
{
    System.debug('-- Creating an exception -- '+(2/0));
}
Apex Class
public class DemoClass 
{
    public void demoMethod()
    {
        Try
        {
            System.debug('--Entered--');
            Account acc = new Account(Name='Test');
            insert acc;
            System.debug('-account created --'+acc.Id);
            Contact con = new Contact(LastName='TestCon');
            insert con;
            System.debug('--Contact created'+con.Id);
        }
        catch(Exception exe)
        {
            System.debug('created new error log');
        }
    }
}
Résolution
If you do not want to allow any DML Statements in case of any failure in trigger, you can use the following Trigger and class like below:
Trigger
trigger TheTrigger on Account (before insert, after insert)
{
    try
    {
     System.debug('-- Throw an exception -- '+(2/0));   
    }
    catch(Exception exe)
    {
       DemoClass.stopTheExecution=false;
    }     
}
Apex Class
public class DemoClass 
{
    Public Static Boolean stopTheExecution=true;
    public void demoMethod()
    {
        Try
        {   
            Savepoint sp = Database.setSavepoint();         
            Account acc = new Account(Name='Test');
            insert acc;
            if(stopTheExecution==false)
            Database.rollback(sp);
            Savepoint sp2 = Database.setSavepoint();  
            System.debug('--account created ?-- '+acc.Id);
            Contact con = new Contact(LastName='TestCon');
            insert con;
            System.debug('--Contact created '+con.Id+ ' ====Static 
            variable== '+stopTheExecution);
            if(stopTheExecution==false)
            Database.rollback(sp2);           
        }
        catch(Exception exe)
        {
            System.debug('Handle Exception or create error log');
        }
    }
}

Please check Transaction Control for rules of using SavePoint and Rollback methods
Numéro d’article de la base de connaissances

000383729

 
Chargement
Salesforce Help | Article