# How do you handle partial success and error isolation when performing DML updates in Batch Apex?

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

Read it on the site: https://www.forcechallenges.com/interview-questions/how-do-you-handle-partial-success-and-error-isolation-when-performing-dml-updates-in-batch-apex

## Answer

**Basics:** A plain `update` fails the entire chunk if one record fails. With `allOrNone=false`, valid records are saved and each failure is reported per record, so one bad row does not block 199 good ones.

**How it works:**
1. Call `Database.update(scope, false)` and capture `List<Database.SaveResult>`.
2. Loop with an index; for each failed result, read `getErrors()` and `scope[i].Id`.
3. Store failures (Stateful list, a log object, or a platform event).
4. Report in `finish()`.

**Advanced / deep dive:** Partial success covers DML-level errors such as validation, required fields and trigger `addError`; it does not stop uncatchable limit exceptions, which roll back the whole chunk. For unhandled exceptions, implement `Database.RaisesPlatformEvents` on the batch class so Salesforce publishes `BatchApexErrorEvent` records that a trigger can consume to log failures. Using `Database.Stateful` to accumulate errors costs heap, so persist logs to a custom object (insert once per chunk) instead of growing a list forever. Upsert returns `UpsertResult`, delete returns `DeleteResult`. Remember that partial success means a record rolled back from a validation rule still counted its DML row.

**Code / config example:**
```apex
public void execute(Database.BatchableContext bc, List<Account> scope) {
    for (Account a : scope) { a.Rating = 'Hot'; }
    List<Database.SaveResult> results = Database.update(scope, false);
    List<Error_Log__c> logs = new List<Error_Log__c>();
    for (Integer i = 0; i < results.size(); i++) {
        if (!results[i].isSuccess()) {
            logs.add(new Error_Log__c(
                Record_Id__c = scope[i].Id,
                Message__c = results[i].getErrors()[0].getMessage()
            ));
        }
    }
    if (!logs.isEmpty()) insert logs; // one DML per chunk, not per record
}
```

**Hidden gotchas & must-remember points:**
- `Database.RaisesErrors` is not a real interface; `Database.RaisesPlatformEvents` is.
- Results align by index with the input list.
- Limit exceptions cannot be caught and fail the entire chunk.
- Partial success still fires triggers on all records, and rolled-back records are not undone in the trigger's side effects until the savepoint behavior applies.
- Catching `DmlException` only works with `allOrNone=true`.
- Each failed chunk still lets other chunks continue.

**Best practice:** Always use partial success in batch, persist failures to a log object, and enable `BatchApexErrorEvent` for the unexpected ones.

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