Sub topic 14
Errors in Queueable, Batch, and other asynchronous Apex
This chapter assumes you can write try/catch/finally blocks, define custom exceptions, and handle DmlException (earlier chapters). You should also know the basics of Queueable, Batch, and @future Apex.
Why asynchronous errors are different
When a synchronous transaction fails, the exception travels back up the call stack to your caller. The caller can catch it, show a message, or let the transaction roll back.
Asynchronous Apex has no caller waiting. System.enqueueJob returns a job ID as soon as the job is queued. The job runs later in its own transaction. If that transaction throws an exception nobody catches, the caller never finds out.
Three consequences follow:
- A
try/catcharoundSystem.enqueueJobcatches only enqueue problems, such as exceeding the limit on queued jobs. It does not catch errors thrown while the job runs. - An uncaught exception rolls back that job's transaction. The job ends with a failed status and Salesforce does not retry it.
- You must handle, record, or report errors inside the asynchronous code, or in a mechanism attached to it.
What happens when each type fails
| Mechanism | Unhandled exception effect | Where you can observe it |
|---|---|---|
| `@future` method | That call's transaction rolls back. Nothing returns to the caller. | Apex Jobs page, Apex Exception Email, debug logs |
| Queueable | That job fails and rolls back. Chained jobs it would have enqueued are not enqueued. | `AsyncApexJob`, a Finalizer, Apex Exception Email |
| Batch | Only the failing `execute` chunk rolls back. Other chunks continue and `finish` still runs. | `AsyncApexJob.NumberOfErrors`, `BatchApexErrorEvent` |
| Schedulable | That run fails. The schedule stays in place and fires next time. | Apex Jobs page, Apex Exception Email |
Administrators can choose who receives unhandled-exception emails in Setup under Apex Exception Email. Email is a poor primary monitoring tool, so the sections below cover better options.
Queueable: catch inside, or attach a Finalizer
The simplest approach is a try/catch inside execute, as in synchronous code. That handles exceptions you expect. It cannot handle limit exceptions such as System.LimitException, which cannot be caught (see the chapter on uncatchable limit exceptions).
A Finalizer covers that gap. It is a class that implements System.Finalizer. Salesforce runs it in a separate transaction after the queueable finishes, whether the job succeeded, threw an exception, or hit a limit. You attach it from inside execute with System.attachFinalizer. A job can have only one finalizer.
The finalizer receives a FinalizerContext:
getResult()returnsParentJobResult.SUCCESSorParentJobResult.UNHANDLED_EXCEPTION.getException()returns the exception that ended the job.getAsyncApexJobId()returns the ID of the failed job.
This example retries a failed job up to three times. Each class goes in its own file.
public class SyncAccountsJob implements Queueable {
private List<Id> accountIds;
private Integer attempt;
public SyncAccountsJob(List<Id> accountIds, Integer attempt) {
this.accountIds = accountIds;
this.attempt = attempt;
}
public void execute(QueueableContext ctx) {
System.attachFinalizer(new SyncAccountsFinalizer(accountIds, attempt));
List<Account> accts = [SELECT Id, Description FROM Account WHERE Id IN :accountIds];
for (Account a : accts) {
a.Description = 'Synced';
}
update accts;
}
}public class SyncAccountsFinalizer implements Finalizer {
private List<Id> accountIds;
private Integer attempt;
public SyncAccountsFinalizer(List<Id> accountIds, Integer attempt) {
this.accountIds = accountIds;
this.attempt = attempt;
}
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
System.debug(LoggingLevel.ERROR,
'Job ' + ctx.getAsyncApexJobId() + ' failed: ' + ctx.getException().getMessage());
if (attempt < 3) {
System.enqueueJob(new SyncAccountsJob(accountIds, attempt + 1));
}
}
}
}Start the first attempt with System.enqueueJob(new SyncAccountsJob(ids, 1)).
The finalizer is a new transaction, so the failed job's DML is already rolled back. Anything the finalizer writes, such as an error record, is saved. The finalizer can enqueue only one new queueable job. Salesforce also limits consecutive re-enqueues from finalizers, so keep your own attempt counter as shown. Retrying only makes sense for transient failures such as row locks or callout timeouts. A validation error will fail the same way each time.
Batch: one failed chunk does not stop the job
A batch job runs start once, then execute once per chunk (the scope size, 200 records by default), then finish. Each execute call is its own transaction. If one chunk throws, only that chunk rolls back. Earlier chunks stay committed, later chunks still run, and finish runs at the end.
You have three ways to find out what failed.
1. Partial-success DML with Database.Stateful. Use Database.update(scope, false) so one bad record does not fail the chunk. Collect the failures in an instance variable. Implementing Database.Stateful keeps instance variables between chunks.
2. Check the job in finish. Query AsyncApexJob using bc.getJobId() and read NumberOfErrors, JobItemsProcessed, TotalJobItems, and Status.
3. Listen for BatchApexErrorEvent. If the class implements Database.RaisesPlatformEvents, Salesforce publishes this platform event when an unhandled exception ends a chunk. The event carries AsyncApexJobId, ExceptionType, Message, StackTrace, Phase, and JobScope (the IDs of the failed records).
public class AccountCleanupBatch implements
Database.Batchable<SObject>, Database.Stateful, Database.RaisesPlatformEvents {
private Integer failedRecords = 0;
private List<String> failureMessages = new List<String>();
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id, Description FROM Account');
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Description = 'Cleaned';
}
List<Database.SaveResult> results = Database.update(scope, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
failedRecords++;
if (failureMessages.size() < 20) {
failureMessages.add(scope[i].Id + ': ' + results[i].getErrors()[0].getMessage());
}
}
}
}
public void finish(Database.BatchableContext bc) {
AsyncApexJob job = [
SELECT Status, NumberOfErrors, JobItemsProcessed, TotalJobItems
FROM AsyncApexJob WHERE Id = :bc.getJobId()
];
System.debug('Batch ' + job.Status + '. Chunk errors: ' + job.NumberOfErrors
+ ', record failures: ' + failedRecords);
for (String msg : failureMessages) {
System.debug(msg);
}
}
}A trigger on the error event handles failures that bypass your own catch logic:
trigger BatchErrorTrigger on BatchApexErrorEvent (after insert) {
for (BatchApexErrorEvent evt : Trigger.new) {
System.debug(LoggingLevel.ERROR, 'Batch job ' + evt.AsyncApexJobId + ' failed with '
+ evt.ExceptionType + ': ' + evt.Message + ' for records ' + evt.JobScope);
}
}Future methods and scheduled jobs
An @future method returns void, so it cannot hand an error back. Wrap its body in try/catch and record the failure somewhere durable, such as a custom log object or a platform event. Otherwise the only trace is the Apex Jobs page and a debug log.
A Schedulable class should do little work. A common design is for execute to enqueue a queueable or batch job, so you handle errors with the tools above. If scheduled code throws, that run fails, but the schedule stays active and the next run still fires.
Testing async error handling
Asynchronous code runs inside a test only when you call Test.startTest() and Test.stopTest(). Everything enqueued between them runs synchronously when stopTest is called. An uncaught exception in the job surfaces at that point and fails the test. To test a failure path, make the job fail on purpose, for example with invalid data. Then assert on the result: the finalizer's side effects, or the state your catch block recorded.
Platform event triggers fire only after delivery. In a test, call Test.getEventBus().deliver() before asserting on the work done by a BatchApexErrorEvent trigger.
Design checklist
- Decide for each job whether failure should be visible (rethrow) or absorbed (log and continue).
- Use partial-success DML in batches so one bad record does not roll back 199 good ones.
- Attach a finalizer to queueables where a limit failure or lost work would matter.
- Retry only transient failures, and cap the attempts.
- Write errors somewhere searchable, because no caller is there to receive them.
Exercise
A batch class processes 1,000 records with a scope size of 200. The third chunk throws an unhandled exception inside execute, and the class does not use Database.update(scope, false). Which records are saved, does finish run, and what is NumberOfErrors? Name one way to learn which records were in the failed chunk.
Show answer
Chunks 1, 2, 4, and 5 commit (800 records), because each execute call is its own transaction. Chunk 3 rolls back, so its 200 records are not saved. finish still runs, and NumberOfErrors is 1, because it counts failed chunks. To find the failed records, implement Database.RaisesPlatformEvents and read JobScope from the BatchApexErrorEvent for that job.
Exercise
Why does a try/catch around System.enqueueJob(new SyncAccountsJob(ids, 1)) not catch a DmlException thrown inside the job, and what should you use instead?
Show answer
The job runs later in a separate transaction, after enqueueJob has already returned, so the exception never passes through the caller's try block. Catch the exception inside the job's execute method, or attach a Finalizer with System.attachFinalizer and inspect ctx.getException() when ctx.getResult() is UNHANDLED_EXCEPTION.