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
sweta kumari 55sweta kumari 55 

How to save Apex batch errors in the Object(Error_Log__c).

Hi All,
Those user record get updated success and those user are not getting update that record created as a  Error record in Error_Log
Here is my code, I am getting inserted any error Log,Please check and let me know the correct logic.
userupdate__c(Custom Setting)
 Error_Log__c (Custom Object)
User(standard Object)

 
public class TestBatchDemo implements Database.Batchable<SObject> 
{     
  public Database.QueryLocator start(Database.BatchableContext bc)   
  {      
   List<userupdate__c> objBatchSize= userupdate__c.getAll().values();    
  List<String> updateuse = new List<string>();       
  for(userupdate__c Au :objBatchSize)
{           
  updateuse.add(Au.UserName__c);           
  System.debug('updateuse'+updateuse);       
  }       
  System.debug('objBatchSize'+objBatchSize);        
 string query = 'select id,UserName,IsActive,firstName from User where UserName Not IN :updateuse';         
System.debug('query'+query);        
 return  Database.getQueryLocator(query);            
  }     public void execute(Database.BatchableContext bc , List<User> UpdateIsActive) 
    {      
  // List< User > Userupda = new List<User>();      
 
    for(User use: UpdateIsActive)     
      {                       
 use.IsActive = false;             
 use.Response__c='Update sucessfully';             
 System.debug('use' +use);                  
  try         {            
Database.update (UpdateIsActive,false);     
       }                     
   catch(exception ex)          
     {                   
List<Error_Log__c> errorLogList  = New List<Error_Log__c>();   
  Error_Log__c log = new Error_Log__c( Object_Name__c  = 'User',Record_Id__c  =use.Id, Request__c =use.Username,   Response__c ='error message'+ex.getMessage());          errorLogList.add(log);       
 Database.SaveResult[] saveResultList = Database.insert(errorLogList, false);                             
     for (Database.SaveResult sr : saveResultList) { 
 if (!sr.isSuccess()) 
{  
System.debug('Successfully inserted error log. error log ID: ' + sr.getId());  }  
else              
   {                   
  for(Database.Error err : sr.getErrors()) {          
   System.debug('The following error has occurred.');                
      System.debug(err.getStatusCode() + ': ' + err.getMessage()); 
 System.debug('REcord fields that  affected this error: ' + err.getFields());  
}  }  }}}}  }          
   public void finish(Database.BatchableContext bc)     {       
  System.debug('Batch is updated');     } }
 
PriyaPriya (Salesforce Developers) 
Hey Sweta,


To save Apex batch job errors in Object you can use  e.getStackTraceString() method in your Batch class execution method
and save this data to the Stacktrace__c  field in your logs custom object.

https://salesforce.stackexchange.com/questions/34207/custom-error-logging-batch-apex-failure-success-counts

Also Refer this document :- 
https://developer.salesforce.com/forums/?id=9062I000000BjzmQAC

If you find your Solution then mark this as the best answer. 

Thank you!
Priya Ranjan
mukesh guptamukesh gupta
Hi Sweta,

You can check my previous best answer:-

https://developer.salesforce.com/forums/?id=9062I000000BjzmQAC

Or you can use below code:-
 
global class IBNext_DownloadCleanupBatchJob implements Database.Batchable<sObject>{
    global List<sObject> start(Database.BatchableContext c)
    {   
    
        List<IDownload_Tracker__c> dbcList=[select  Request_Date__c,Content_Document__c,Content_Version__c,Download_Filename__c,Download_URL__c,Download_User__c,Subject__c,Recipient_Email_1__c from Download_Tracker__c where CreatedDate < TODAY];
       
        List<Id> cvID=new List<Id>();
        List<Id> cdid=new List<Id>(); 
        List<sObject> allobjects=new List<sObject> ();
      
        for(Download_Tracker__c edrtObject:dbcList){
               cvID.add(edrtObject.Content_Version__c);
               cdid.add(edrtObject.Content_Document__c);
        }
        allobjects.addAll([select Id from ContentDistribution where ContentVersionId IN: cvID]);
        allobjects.addAll([select Id from ContentDocument where Id IN: cdid]);
        allobjects.addAll((List<sObject> )(dbcList));
        system.debug('*********AllObjects**********'+allobjects);
        return allobjects;
    }
    //global void execute(Database.BatchableContext c, List<Download_Tracker__c> scope)
    global void execute(Database.BatchableContext c, List<sObject> scope)
    {
        try
        { 
        delete scope;
        }
        catch(Exception ex) 
        { 
		List<Error_Log__c> errorLogList  = New List<Error_Log__c>();
		Error_Log__c log = new Error_Log__c( Error_Message__c = 'Job Status: ' + ex.getMessage(),
                                              Apex_Class_Name__c = 'DownloadCleanupBatchJob');
         errorLogList.add(log); 
		  
		  Database.SaveResult[] saveResultList = Database.insert(errorLogList, false);

			// Iterate through saveResultList based on isSuccess capture the failed records
			for (Database.SaveResult sr : saveResultList) {
				if (!sr.isSuccess()) {
					// Operation was successful, so get the ID of the record that was processed
					System.debug('Successfully inserted error log. error log 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('REcord fields that affected this error: ' + err.getFields());
					}
				}
			}

		  
		  
        }
    }         
    // Finish Method
    global void finish(Database.BatchableContext BC) {
    }
    }


if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh