Sub topic 14
Errors in Queueable, Batch, and other asynchronous Apex
This chapter assumes you know try/catch/finally, custom exceptions, and how Database.insert reports partial failures.
Why asynchronous errors are different
Asynchronous Apex runs in its own transaction, after the code that started it has finished. A try/catch around System.enqueueJob() or Database.executeBatch() catches only problems with queuing the job. It cannot catch anything the job throws later.
If a job throws an exception that nothing catches, the platform rolls back that job's transaction and marks the job as failed. You can see the failure in Setup > Apex Jobs. Nobody is notified unless your code does it.
Queueable: catch inside, add a finalizer
Handle expected errors inside execute, as in synchronous code. For errors you did not expect, attach a finalizer. A finalizer is a class that implements Finalizer. The platform runs it after the job ends, whether the job succeeded or failed. It also runs when the job hit a governor limit, which you cannot catch.
public class SyncJob implements Queueable {
public void execute(QueueableContext ctx) {
System.attachFinalizer(new SyncFinalizer());
insert new Account(); // fails: Name is required
}
private class SyncFinalizer implements Finalizer {
public void execute(FinalizerContext fc) {
if (fc.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
System.debug(LoggingLevel.ERROR,
'Job ' + fc.getAsyncApexJobId() + ' failed: '
+ fc.getException().getMessage());
}
}
}
}A finalizer can enqueue one new job, so it is a good place to retry. Put a retry counter in the new job so a permanent failure cannot loop forever.
Batch: each chunk is its own transaction
A batch class calls execute once per chunk of records. Each call is a separate transaction. If one chunk throws, only that chunk rolls back. Earlier chunks stay committed, and the remaining chunks still run.
Use partial-success DML and count failures in a Database.Stateful class. Without Database.Stateful, instance variables reset between chunks.
public class CleanupBatch implements Database.Batchable<SObject>, Database.Stateful {
private Integer failures = 0;
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 = null;
}
for (Database.SaveResult sr : Database.update(scope, false)) {
if (!sr.isSuccess()) {
failures++;
}
}
}
public void finish(Database.BatchableContext bc) {
System.debug(failures + ' records failed');
}
}To learn about uncaught chunk failures, declare implements Database.RaisesPlatformEvents. The platform then publishes a BatchApexErrorEvent for each failed chunk. The event has AsyncApexJobId, JobScope, ExceptionType, Message, and StackTrace fields. A trigger on that event can write the details to a log object.
Other asynchronous Apex
- Future methods: The caller cannot catch their exceptions. Catch inside the method and log the error.
- Schedulable: An exception in
executefails the scheduled run. The schedule itself stays active.
Exercise
A Batch Apex job processes 10 chunks. Chunk 4 throws an uncaught exception. What happens to chunks 1 to 3 and chunks 5 to 10, and how can you find out about the failure?
Show answer
Chunks 1 to 3 stay committed, because each chunk is its own transaction. Only chunk 4 rolls back. Chunks 5 to 10 still run. You can see the error in Apex Jobs. To react in code, implement Database.RaisesPlatformEvents and handle BatchApexErrorEvent.