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
Aditi Mohanty 5Aditi Mohanty 5 

I want to add try-catch block in this code. The insert statement will be in try and all the error will be in catch. The insert statement should be written in restApi instead of dml. I also have to send all the errors in mail. How to do that?

global class Batch_AddConToAcc implements Database.Batchable <sObject>,Database.Stateful {
     
    
   String query = 'SELECT Id, Name FROM Account WHERE checkacc__c = True';
    global Database.QueryLocator start(Database.BatchableContext bc) {
         
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext bc,List<Account> batch) {
       List<Account> acnt=new List<Account>();
        List<contact> lstCon = new List<Contact>();
        for (Account a : batch) {
           
            Contact c =  new Contact();
            c.LastName = a.Name;
        
            lstCon.add(c);
            a.checkacc__c = False;  
            acnt.add(a);
          
        }
        
        INSERT lstCon;
       update acnt;
        
        }
    
    global void finish(Database.BatchableContext bc) {
     

AsyncApexJob ajob = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
                          TotalJobItems, CreatedBy.Email
                          FROM AsyncApexJob WHERE Id =
                          :bc.getJobId()];
 EmailUtility.sendSimpleEmail(ajob.Status);      
        
        
     
        }     
       
    }

 
ShirishaShirisha (Salesforce Developers) 
Hi Aditi,

Greetings!

You can simply the try block for the code which has updates/inserts or any  other DML operation and catch block to catch the exceptions.You can refer the below document for the sample code:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_exception_trycatch_example.htm

Also,you can set the Apex exceptions to receive the error mails as suggested here (https://help.salesforce.com/articleView?id=000330030&type=1&mode=1).

Please mark it as best answer if it helps you to fix the issue.

Thank you!

Regards,
Shirisha Pathuri