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

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Error Handling

Read it on the site: https://www.forcechallenges.com/interview-questions/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.

---
Source: ForceChallenges · last updated 2026-11-02
