ForceChallenges
ProblemsDailyNotesInterview
Sign in

Practice

All problemsSOQL practiceApex trigger challengesDaily challengeOpportunityTrigger.oldMapBefore UpdateBulkificationContactValidationGROUP BYSemi-JoinAccountBefore Insert

Interview questions

All questionsAdminAdministrationApexApex TriggerAsync ApexDevelopmentField ServiceField ServiceIntegrationLwc

By company

DeloitteSalesforceAccentureInfosysPwCCognizant

Learn

Study notes

ForceChallenges

AboutContact usPrivacy PolicyTerms of ServiceFor AI assistants (llms.txt)
© 2026 ForceChallenges · Salesforce SOQL & Apex trigger practice
Apex questions35 of 41
ApexMedium 2 min read

What strategies should developers implement for robust error handling and logging in Batch Apex?

Answer

Basics: One uncaught exception fails that chunk and rolls it back, but the job continues with later chunks. If you do nothing you only see an email to the code author and a non-zero NumberOfErrors, with no record-level detail. Good design records exactly which records failed and why, and lets you re-run just those.

How it works: In execute, use Database.update(records, false) and loop over SaveResult to capture per-row errors (getErrors(), getStatusCode(), getFields()). Wrap callouts or complex logic in try/catch. Persist failures to a log object, or accumulate a bounded list in a Stateful member and send a summary from finish. Implement Database.RaisesPlatformEvents to have the platform publish a BatchApexErrorEvent when a chunk throws an unhandled exception, including catastrophic ones you cannot catch; a trigger on that event can log or retry.

Advanced / deep dive: The catch: log rows inserted in the same transaction that later fails are rolled back with it, so logging inside a failing chunk is unreliable. Solutions: publish a platform event configured to publish immediately, use BatchApexErrorEvent, or log in a Finalizer-like construct. Limit exceptions (CPU, heap, too many SOQL) are not catchable, so test with realistic volumes and rely on the error event. Add a retry strategy: store failed record Ids in a log with a retry count, and use a scheduled or chained job to re-process those with a smaller scope, giving up after N attempts. Make operations idempotent so reruns do not duplicate work. Classify errors (transient lock or timeout versus permanent validation) and only retry transient ones. Notify via custom notification, Slack, or email from finish using AsyncApexJob counts.

Code / config example:

apex
public class SafeBatch implements Database.Batchable<SObject>, Database.Stateful, Database.RaisesPlatformEvents {
    private Integer failures = 0;
    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT Id, Status__c FROM Case WHERE Status__c = \'New\'');
    }
    public void execute(Database.BatchableContext bc, List<Case> scope) {
        for (Case c : scope) c.Status__c = 'Processed';
        List<Database.SaveResult> res = Database.update(scope, false);
        List<Batch_Error__c> logs = new List<Batch_Error__c>();
        for (Integer i = 0; i < res.size(); i++) {
            if (!res[i].isSuccess()) {
                failures++;
                logs.add(new Batch_Error__c(Record_Id__c = scope[i].Id,
                    Message__c = res[i].getErrors()[0].getMessage().left(255)));
            }
        }
        if (!logs.isEmpty()) insert logs;
    }
    public void finish(Database.BatchableContext bc) {
        if (failures > 0) System.debug('Batch finished with ' + failures + ' failures');
    }
}

Hidden gotchas & must-remember points:

  • Database.RaisesPlatformEvents is the real interface; Database.RaisesErrors does not exist.
  • Logs written in a rolled-back chunk disappear unless sent via an immediately published event.
  • Governor limit exceptions cannot be caught; only the error event or finalizer-style handling sees them.
  • Partial-success DML returns errors, it does not throw; ignoring SaveResult hides failures.
  • finish runs even if some chunks failed.
  • Keep error text within field length limits.

Best practice: Use partial-success DML, a durable log, BatchApexErrorEvent, and idempotent retries with a retry cap.

ApexAsynchronous ApexError Handling
Practice SOQL & Apex
PreviousWhat are the best practices for handling parent-child relationships across Batch Apex chunks?Next How can you pass non-primitive collections into Queueable Apex jobs for processing?

More Apex questions

  • How do you pass runtime parameters into a Batch Apex class prior to execution?
  • What are the primary differences in governor limits between synchronous transactions and asynchronous Apex executions?
  • How do you prevent recursive asynchronous job enqueuing triggered by recursive database DML updates?
  • How can you trigger subsequent asynchronous jobs inside the finish method of a Batch Apex class?
  • How can you track the execution identifier returned when enqueueing a Queueable Apex job?