Sub topic 11
Reading the result with FinalizerContext
This chapter assumes you can write a Queueable class, attach a finalizer with System.attachFinalizer, and read AsyncApexJob records. Here you learn what the platform passes to a finalizer's execute method and how to read it safely.
What a finalizer receives
A finalizer implements the Finalizer interface, which has one method: execute(FinalizerContext ctx). The platform calls it after the parent queueable's transaction ends. It calls it whether the parent succeeded or failed.
The finalizer runs in its own transaction with its own governor limits. It does not share the parent's heap or query count. Anything the parent left uncommitted when it failed has already been rolled back by the time the finalizer starts.
The FinalizerContext object is how the finalizer learns what happened in the parent.
| Method | Return type | What it gives you |
|---|---|---|
| `getAsyncApexJobId()` | `Id` | The ID of the parent queueable's `AsyncApexJob` record |
| `getResult()` | `ParentJobResult` | `SUCCESS` or `UNHANDLED_EXCEPTION` |
| `getException()` | `System.Exception` | The unhandled exception, or `null` when the parent succeeded |
| `getRequestId()` | `String` | The request ID shared by the parent and the finalizer |
ParentJobResult is an enum with two values: SUCCESS and UNHANDLED_EXCEPTION. A branch on it covers every outcome the platform reports.
The result describes the parent's transaction
UNHANDLED_EXCEPTION means the parent's execute method ended with an exception that nothing caught. If your code catches an exception inside execute and returns normally, the platform sees a successful transaction. The finalizer then receives SUCCESS, even though your code hit a problem.
That has a practical consequence. If you want the finalizer to react to a failure, let the exception escape. Catching and swallowing it hides the failure from the finalizer. If you catch an exception to add context, rethrow it:
try {
// risky work
} catch (DmlException e) {
System.debug(LoggingLevel.ERROR, 'Import step failed: ' + e.getMessage());
throw e;
}Uncatchable limit exceptions also count as unhandled. Examples are too many SOQL queries or heap size exceeded. A try/catch cannot stop them, so a finalizer is one of the few places where your code gets to react to them. Be aware of one consequence. A limit failure rolls back the parent's work, so retrying the same input may hit the same limit again.
Reading the context
This example shows a queueable with a finalizer that reads all four values. The parent deliberately throws when told to, so you can see the failure path.
public class SyncJob implements Queueable {
private List<Id> recordIds;
private Boolean failOnPurpose;
public SyncJob(List<Id> recordIds, Boolean failOnPurpose) {
this.recordIds = recordIds;
this.failOnPurpose = failOnPurpose;
}
public void execute(QueueableContext context) {
System.attachFinalizer(new SyncFinalizer(recordIds));
if (failOnPurpose) {
throw new IllegalArgumentException('Simulated failure');
}
// Normal work goes here.
}
}
public class SyncFinalizer implements Finalizer {
private List<Id> recordIds;
public SyncFinalizer(List<Id> recordIds) {
this.recordIds = recordIds;
}
public void execute(FinalizerContext ctx) {
Id parentJobId = ctx.getAsyncApexJobId();
String requestId = ctx.getRequestId();
switch on ctx.getResult() {
when SUCCESS {
System.debug('Job ' + parentJobId + ' succeeded. Request ' + requestId);
}
when UNHANDLED_EXCEPTION {
Exception ex = ctx.getException();
System.debug(LoggingLevel.ERROR,
'Job ' + parentJobId + ' failed with '
+ ex.getTypeName() + ': ' + ex.getMessage()
+ ' for ' + recordIds.size() + ' records. Request ' + requestId);
}
}
}
}Three details are worth noting.
- The finalizer is attached as the first statement in
execute. If you attach it after code that throws, the platform never registers it, and nothing runs after the failure. - The finalizer carries its own state,
recordIds, through its constructor. It does not read the parent's variables. The finalizer is a separate object, so pass it whatever it needs. getException()is only safe to dereference in theUNHANDLED_EXCEPTIONbranch. On success it returnsnull, and calling a method on it throws aNullPointerExceptioninside your finalizer.
How the pieces fit together
Using the job ID to look up more detail
getAsyncApexJobId() returns the ID of the parent job. You can query AsyncApexJob for facts the context does not carry directly, such as who enqueued the job and when it was created:
public void execute(FinalizerContext ctx) {
AsyncApexJob job = [
SELECT Id, Status, CreatedDate, CreatedById, ExtendedStatus
FROM AsyncApexJob
WHERE Id = :ctx.getAsyncApexJobId()
];
System.debug('Parent job created by ' + job.CreatedById
+ ' at ' + job.CreatedDate + ', status ' + job.Status);
}This query counts against the finalizer's own limits, not the parent's. The status you see may not yet read as final. Treat getResult() as the source of truth for success or failure, and use the query for supporting detail such as user and timestamps.
Using the request ID to correlate logs
The parent and the finalizer share a request ID. When you write a log entry from the finalizer, include getRequestId() and, if you also log from the parent, include the same value there with System.Request.getCurrent().getRequestId(). A single search on that value then finds the log lines from both transactions.
Common mistakes
- Swallowing the exception in the parent. The finalizer reports
SUCCESS, and a retry pattern never triggers. - Calling
getException()without checking the result. It returnsnullon success. - Expecting parent state in the finalizer. The finalizer only sees what you passed to its constructor. Variables set during the parent's
executeare not visible to it. - Assuming partial work survived. When the parent fails with an unhandled exception, its DML is rolled back. The finalizer must treat the whole slice as not done.
- Putting risky logic in the finalizer. If the finalizer throws, nothing retries it. Keep it short: read the context, log, and optionally enqueue.
Branching on more than success or failure
getResult() gives only two outcomes. If you need a finer distinction, inspect the exception's type. Distinguishing a DmlException from a CalloutException lets you choose a different action. For example, you can retry callout failures and send data errors to a review list:
Exception ex = ctx.getException();
if (ex instanceof CalloutException) {
// Transient: worth a retry
} else if (ex instanceof DmlException) {
// Data problem: log for review, do not retry blindly
}A limit exception is not catchable in the parent, but it still appears here as the exception object. Calling getTypeName() on it returns System.LimitException.
The next chapter builds on this to implement bounded retries, using the result and exception from the context to decide whether to enqueue the job again.
Exercise
A queueable's execute method wraps all of its work in try/catch (Exception e) and calls System.debug(e.getMessage()) without rethrowing. The work fails with a DmlException. What does the attached finalizer see in ctx.getResult(), and what does ctx.getException() return?
Show answer
ctx.getResult() returns ParentJobResult.SUCCESS, because the exception was caught and the parent transaction completed normally. ctx.getException() returns null. To let the finalizer see the failure, rethrow the exception (or do not catch it) so it ends the parent's execute method as an unhandled exception.
Exercise
Write the body of a Finalizer's execute(FinalizerContext ctx) method that logs the parent job ID and the exception message only when the parent failed, and does nothing when it succeeded.
Show answer
public void execute(FinalizerContext ctx) { if (ctx.getResult() == ParentJobResult.SUCCESS) { return; } System.debug(LoggingLevel.ERROR, 'Job ' + ctx.getAsyncApexJobId() + ' failed: ' + ctx.getException().getMessage()); }