Loading
Salesforce から送信されるメールは、承認済ドメインからのみとなります続きを読む

例外処理による Apex クラスとトリガーのトランザクション制御

公開日: Oct 13, 2022
説明
※この記事は英語版を翻訳しており、一部機械翻訳を含むため内容は後日更新される可能性があります。最新の内容は英語版を参照してください。表示言語は画面右下の言語名から切り替えられます。

例外処理が設計されている Apex クラスから DML が開始された場合、実行の一部としてトリガーに入ります。例外が発生した場合、制御は Apex クラスの catch ブロックに戻りません。これは想定内です。 

以下にこの動作を説明するサンプルトリガーと Apex クラスを示します。
trigger TheTrigger on Account (before insert, after insert)
{
    System.debug('-- Creating an exception -- '+(2/0));
}
Apex クラス
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');
        }
    }
}
解決策
トリガーに失敗した場合に DML ステートメントを許可しない場合は、次のようなトリガーとクラスを使用できます。
トリガー
{
    try
    {
     System.debug('-- Throw an exception -- '+(2/0));   
    }
    
    {
       DemoClass.stopTheExecution=false;
    }     
}
Apex クラス
 
{
    Public Static Boolean stopTheExecution=true;
    
    {
        
        {   
            Savepoint sp = Database.setSavepoint();         
            
            
            if(stopTheExecution==false)
            Database.rollback(sp);
            Savepoint sp2 = Database.setSavepoint();  
            System.debug('--account created ?-- '+acc.Id);
            
            
            System.debug('--Contact created '+con.Id+ ' ====Static 
            variable== '+stopTheExecution);
            if(stopTheExecution==false)
            Database.rollback(sp2);           
        }
        
        {
            System.debug('Handle Exception or create error log');
        }
    }
}

SavePoint と Rollback メソッドの使用ルールについては、「トランザクションの制御」を参照してください。
ナレッジ記事番号

000383729

 
読み込み中
Salesforce Help | Article