Sub topic 11
Handling failures and using Finalizers
This chapter assumes you can write a trigger and a Queueable class that implements Database.AllowsCallouts, and that you know the HTTP callout classes. Earlier chapters showed the happy path. Here you decide what happens when the callout does not work.
What can go wrong in an async callout
A trigger hands the work to a Queueable job, and the trigger transaction then finishes. If the job fails later, no user sees an error and nothing rolls back the original insert. The account stays in Salesforce, but the external system never hears about it. You have to build the failure handling yourself.
Failures fall into four groups:
| Failure | How it shows up | Retry? |
|---|---|---|
| Network problem or timeout | `System.CalloutException` thrown by `Http.send` | Usually yes |
| Server error (500, 502, 503) | Normal `HttpResponse` with a 5xx status code | Usually yes |
| Client error (400, 401, 404, 422) | Normal `HttpResponse` with a 4xx status code | No, the same request fails again |
| Limit or other unhandled error | Unhandled exception, job ends as failed | Depends on the cause |
Apex only throws for the first group. A 400 or 500 response is a valid HTTP response, so send returns it without error. If you never read the status code, the job reports success even though the remote system rejected the data.
Check the status code
The minimum is to read the status code after every send. The earlier AccountSyncJob did this with a System.debug. A debug line is only visible while a debug log is running, so it is weak evidence in production. Choose between three actions for each response:
- 2xx: do nothing more.
- 5xx: the remote side may recover, so throw an exception and let retry logic take over.
- 4xx: the request itself is wrong. Record the failure and stop, because a retry only repeats it.
What a Finalizer is
A Finalizer is a class that implements the Finalizer interface. You attach it from inside a Queueable's execute method with System.attachFinalizer. Salesforce runs it after the job ends, whether the job succeeded or failed with an unhandled exception.
Facts to remember:
- A job can have only one Finalizer. Attach it as the first statement in
execute. If the job fails before the attach call, no Finalizer runs. - The Finalizer runs in its own transaction with its own governor limits.
- When the job fails with an unhandled exception, its DML is rolled back. The Finalizer's DML is not rolled back, so it can safely write a log record.
- A Finalizer also runs after an uncatchable limit exception. A
try/catchblock cannot cover that case. - A Finalizer can enqueue one new Queueable job. This is how you build a retry.
FinalizerContextgives yougetResult(),getException(),getAsyncApexJobId()andgetRequestId().
getResult() returns a ParentJobResult. Its values are SUCCESS and UNHANDLED_EXCEPTION.
A job that retries
The next version of the job keeps an attempt counter. It throws on a 5xx response and handles a 4xx response without throwing. The thrown exception makes the Finalizer see UNHANDLED_EXCEPTION.
public class AccountSyncRetryJob implements Queueable, Database.AllowsCallouts {
public class SyncException extends Exception {}
public static final Integer MAX_ATTEMPTS = 3;
private Set<Id> accountIds;
private Integer attempt;
public AccountSyncRetryJob(Set<Id> accountIds, Integer attempt) {
this.accountIds = accountIds;
this.attempt = attempt;
}
public void execute(QueueableContext ctx) {
System.attachFinalizer(new AccountSyncRetryFinalizer(accountIds, attempt));
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
List<Map<String, Object>> payload = new List<Map<String, Object>>();
for (Account a : accounts) {
payload.add(new Map<String, Object>{ 'id' => a.Id, 'name' => a.Name });
}
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(20000);
req.setBody(JSON.serialize(payload));
HttpResponse res = new Http().send(req);
Integer code = res.getStatusCode();
if (code >= 500) {
// Temporary problem on the remote side: fail so the Finalizer retries.
throw new SyncException('Server error ' + code + ': ' + res.getBody());
} else if (code >= 400) {
// Permanent problem with the request: retrying would repeat it.
System.debug(LoggingLevel.ERROR,
'Rejected by remote system (' + code + '): ' + res.getBody());
}
}
}The trigger now starts the first attempt:
trigger AccountSyncTrigger on Account (after insert) {
System.enqueueJob(new AccountSyncRetryJob(Trigger.newMap.keySet(), 1));
}A Finalizer that decides what to do
The Finalizer receives the same Ids and attempt number through its constructor. It only acts when the job failed.
public class AccountSyncRetryFinalizer implements Finalizer {
private Set<Id> accountIds;
private Integer attempt;
public AccountSyncRetryFinalizer(Set<Id> accountIds, Integer attempt) {
this.accountIds = accountIds;
this.attempt = attempt;
}
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.SUCCESS) {
return;
}
String message = ctx.getException() == null
? 'unknown error'
: ctx.getException().getMessage();
if (attempt < AccountSyncRetryJob.MAX_ATTEMPTS) {
System.debug(LoggingLevel.WARN, 'Attempt ' + attempt + ' failed: ' + message
+ '. Retrying job ' + ctx.getAsyncApexJobId());
System.enqueueJob(new AccountSyncRetryJob(accountIds, attempt + 1));
} else {
System.debug(LoggingLevel.ERROR, 'Giving up after ' + attempt
+ ' attempts for ' + accountIds.size() + ' accounts: ' + message);
// Write a custom log record here so an admin can find and replay the failure.
}
}
}Three design points matter here:
- The attempt limit stops an endless loop. Without it, a remote system that is down for a day would produce a chain of jobs that never ends.
- The Finalizer has access to constructor state, not the job's local variables. Pass in whatever it needs. Passing Ids, not records, matches the rule from the chapter on passing data.
- A Finalizer can enqueue only one job. If you split work into several jobs, retry them from a single parent job.
Idempotency and partial success
A retry sends the same data again. If the first attempt actually reached the server and only the response was lost, the second attempt creates a duplicate unless the remote API deduplicates. Send a stable key, such as the Salesforce Id, as in 'id' => a.Id, and ask the remote system to upsert on it.
A bulk request can also partly succeed. Some APIs return 200 with a per-record error list in the body. Parse the body and treat those errors as failures. The status code alone does not tell you everything.
Future methods have no Finalizer
A @future method has no equivalent of System.attachFinalizer. You can wrap the callout in try/catch and write a log record in the catch block. For an uncatchable failure, such as a limit exception, nothing runs afterward. This is one reason to prefer Queueable Apex when failure handling matters. The comparison chapter returns to this point.
Where failures are recorded
An unhandled exception in a Queueable shows up in these places:
- The
AsyncApexJobrecord getsStatus = 'Failed'and anExtendedStatusmessage. - The Apex Jobs page in Setup lists the failed job.
- Salesforce can send an Apex exception email to the users configured for it.
None of these prompts anyone to replay the work. If the data matters, have the Finalizer's final branch write a custom log record, or publish a platform event that an admin process watches.
Common mistakes
- Attaching the Finalizer after the callout code. If the callout throws first, no Finalizer is attached.
- Checking only for
CalloutExceptionand ignoring 4xx and 5xx responses. - Retrying 4xx responses. These need a data fix, not another attempt.
- Having no attempt limit.
- Doing the retry decision in a
catchblock insideexecute. Acatchcannot handle limit exceptions, and a Finalizer can.
Exercise
An AccountSyncRetryJob receives HTTP 422 with a body explaining that an account name is invalid. The job does not throw. What happens next, and is that correct? What would happen if the code threw a SyncException for the 422?
Show answer
The job finishes with a success result, so the Finalizer sees ParentJobResult.SUCCESS and returns without retrying. The error is only written to the debug log. That behavior is correct for retrying, because a 422 is a permanent client error and a retry would send the same invalid data. It is weak for visibility, so the code should also write a log record. If the job threw for the 422, the Finalizer would retry up to the attempt limit and fail every time, wasting async job executions.
Exercise
Why must System.attachFinalizer be the first statement in execute, and what in the Finalizer's behavior makes it safer than a try/catch for failure handling?
Show answer
A Finalizer is only registered when the attach statement runs. If the callout or a query throws before that line, no Finalizer exists and nothing runs afterward. A Finalizer is safer than try/catch because it runs in its own transaction after the job ends, including after uncatchable limit exceptions, and its DML is not rolled back with the failed job.