Search code examples
salesforceapex-code

How to get your failing batch records?


Is there a way to get the records in the batches that failed? The AsyncApexJob only gives me the number of failures- but nothing more than that really...

http://www.salesforce.com/us/developer/docs/object_reference/index_Left.htm#CSHID=sforce_api_objects_asyncapexjob.htm|StartTopic=Content%2Fsforce_api_objects_asyncapexjob.htm|SkinName=webhelp


Solution

  • I don't think there's a way to get all of the desired details using default functionality. I worked around this by creating a Batch Status object where I can log the errors that occur within the batch. Essentially I wrapped my batch execute code in a try/catch block and within the catch, I add a new Batch Status record with the details of the error.

    global void execute(Database.BatchableContext BC, List<sObject> scope) { 
    
        List<Batch_Status__c> BatchStatuses = new List<Batch_Status__c>();
    
        try {
            // ... batch execute code ...
        }
        catch(Exception e) {
            // exception logging
            Batch_Status__c BatchStatus = new Batch_Status__c();
    
            // ... add exception detail to BatchStatus ...
            BatchStatuses.add(BatchStatus);
        }
    
        insert BatchStatuses;
    }