Sub topic 6
Transaction Finalizers for cleanup and failure handling
This chapter assumes you can write a Queueable class and enqueue it with System.enqueueJob, and that you know how governor limits and unhandled exceptions behave in a single transaction.
The problem: a failed job leaves no trace
A Queueable job runs in its own transaction. If execute throws an exception that nothing catches, Salesforce rolls back the job's changes and marks the job as failed. A try/catch inside execute helps only for errors you can catch. Limit exceptions, such as too many SOQL queries or CPU time exceeded, cannot be caught. In those cases the code after the failure never runs, so you cannot log the error or retry from inside the job.
A Transaction Finalizer solves this. It is a separate class that Salesforce runs after the Queueable job finishes, whether the job succeeded or failed.
How a finalizer works
A finalizer implements the Finalizer interface, which has one method: execute(FinalizerContext ctx). You attach it from inside the Queueable's execute method by calling System.attachFinalizer. Each job can attach only one finalizer, and you can attach it only once per execution.
The finalizer runs in its own transaction. This is why it can do work even when the parent job was rolled back.
The FinalizerContext gives you these details:
| Method | Returns |
|---|---|
| `getResult()` | A `ParentJobResult` value: `SUCCESS` or `UNHANDLED_EXCEPTION` |
| `getException()` | The unhandled exception, or null if the job succeeded |
| `getAsyncApexJobId()` | The Id of the parent job, which you can query in `AsyncApexJob` |
| `getRequestId()` | An Id shared by the parent job and its finalizer, useful for correlating log entries |
Example: log a failure
This finalizer checks the result and logs the exception message when the parent job failed.
public class LogFailureFinalizer implements Finalizer {
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
System.debug(LoggingLevel.ERROR, 'Job failed: ' + ctx.getException().getMessage());
}
}
}Attach it as the first step of the Queueable's execute method. Attaching early matters. If the job fails before it reaches the attach line, no finalizer runs.
public class ReviewWithFinalizerJob implements Queueable {
private List<Account> accounts;
public ReviewWithFinalizerJob(List<Account> accounts) {
this.accounts = accounts;
}
public void execute(QueueableContext ctx) {
System.attachFinalizer(new LogFailureFinalizer());
for (Account a : accounts) {
a.Description = 'Reviewed';
}
update accounts;
}
}Retrying from a finalizer
A finalizer can enqueue a new Queueable job, so it can retry a failed job. Always cap the number of retries. Without a cap, a job that fails every time will re-enqueue itself forever. Pass a retry count through the constructor and stop at a fixed limit, such as three attempts.
Common mistakes
- Attaching the finalizer late in
execute, after code that might fail. - Assuming the parent job's database changes survive. On
UNHANDLED_EXCEPTIONthey are rolled back. - Retrying without a limit.
- Trying to attach a finalizer to a future method or a Batch job. Finalizers apply to Queueable jobs.
Exercise
A Queueable job exceeds the CPU time limit. Why can a try/catch block inside execute not log this failure, and what can you use instead?
Show answer
A CPU time limit exception cannot be caught, so the catch block never runs. Attach a Finalizer with System.attachFinalizer at the start of execute. The finalizer runs in its own transaction afterward, and it can read ctx.getResult() and ctx.getException() to log the error or enqueue a limited retry.
Exercise
Why should System.attachFinalizer be the first statement in the execute method?
Show answer
If the job fails before the attach line runs, no finalizer is registered, so no cleanup or logging happens. Attaching first guarantees the finalizer runs for any later failure.