Sub topic 3
Reading the Result with FinalizerContext
Assume basic Apex classes, SOQL, DML, governor limits, and @IsTest. A transaction finalizer runs after a queueable job finishes. FinalizerContext tells the finalizer what happened to the parent job.
Reading the result
Use getResult() to distinguish success from an unhandled exception. Use getAsyncApexJobId() for logging. Use getException() when the job failed.
public class ImportFinalizer implements Finalizer {
public void execute(FinalizerContext context) {
Id jobId = context.getAsyncApexJobId();
if (context.getResult() == ParentJobResult.SUCCESS) {
System.debug('Job succeeded: ' + jobId);
return;
}
Exception error = context.getException();
System.debug(LoggingLevel.ERROR,
'Job failed: ' + jobId + ', error: ' + error.getMessage());
}
}A finalizer runs in its own transaction. It can inspect the parent job, but it cannot undo work that the failed transaction already rolled back.
Bounded retries and failure logging
A retry must have a limit. Store an attempt number in the queueable and increment it before re-enqueuing.
if (context.getResult() != ParentJobResult.SUCCESS
&& attempt < 3) {
System.enqueueJob(new ImportJob(recordIds, attempt + 1));
}Retry only failures that may succeed later. Do not retry validation errors or permanently invalid data. Log the job ID, attempt, exception message, and record scope.
Rules and limits for finalizers
A queueable can attach one finalizer with System.attachFinalizer. The finalizer has separate governor limits, but it is still asynchronous Apex and cannot perform unlimited work. Keep it small. Avoid retry loops, and remember that a retry creates a new queueable job.
Testing and choosing a tool
Test.stopTest() runs an enqueued queueable during a test.
Test.startTest();
System.enqueueJob(new AccountRatingJob(new List<Id>{ accountId }));
Test.stopTest();
System.assertEquals(
'Hot',
[SELECT Rating FROM Account WHERE Id = :accountId].Rating
);Use a queueable for stateful, monitorable background work. Use a future method for a small, simple asynchronous call. Use Batch Apex when the workload requires many records with batch-level processing.
Exercise
Why should a finalizer retry a failed queueable only a fixed number of times?
Show answer
An unbounded retry can create an endless chain, consume limits, and repeatedly fail on permanent data errors.