Sub topic 11
Handling failures and using Finalizers
This chapter assumes you can write a Queueable class, make an HTTP callout with a Named Credential, and read Apex debug logs. Here you will learn how a callout job can fail and how to detect each kind of failure.
Two kinds of failure
A callout job can fail in two different ways.
- The server answers with an error. The call completes and you get an
HttpResponsewith a status such as 400 or 503. Apex does not throw an exception. You must check the status code yourself. - The job itself fails. A
CalloutException(for example a timeout), aQueryException, or a governor limit error ends the job with an unhandled exception. Nothing after the failing line runs.
The first kind is handled inside execute. The second kind is handled by a Finalizer.
Check the status code
Http.send returns normally for any HTTP response. A 500 is not an exception. The job in this tutorial checks the code like this:
HttpResponse res = new Http().send(req);
if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR, 'Sync failed: ' + res.getStatusCode() + ' ' + res.getBody());
}Logging is the minimum. For a real integration, decide what each status means. A 4xx code usually means the request is wrong, so retrying will not help. A 5xx code or a timeout is often temporary, so a retry may work.
Add a Finalizer
A Finalizer is a class that implements Finalizer. You attach it from inside execute with System.attachFinalizer. It runs after the Queueable finishes, whether the job succeeded or ended with an unhandled exception.
public class AccountSyncFinalizer implements Finalizer {
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
System.debug(LoggingLevel.ERROR, 'Queueable failed: ' + ctx.getException().getMessage());
}
}
}The job attaches it on its first line, before any code that could fail:
public void execute(QueueableContext ctx) {
System.attachFinalizer(new AccountSyncFinalizer());
// query, build the request, send it
}If you attach the Finalizer after the callout, an exception on the callout line means it was never attached.
What a Finalizer can do
The FinalizerContext gives you the result, the exception and the job Id. A Finalizer can log the error, write a record that someone can review, or enqueue a new job to retry. A Finalizer may do these things:
- Run DML and enqueue one new Queueable job.
- Make callouts, if the Finalizer class implements
Database.AllowsCallouts.
A retry needs a limit. If the Finalizer always enqueues the job again, a permanent error such as a bad endpoint creates an endless loop of failing jobs. Pass a retry counter into the job and stop at a fixed number, such as three.
Common mistakes
- Treating a 500 response as success because no exception was thrown.
- Attaching the Finalizer late in
execute. - Retrying without a counter.
- Putting a callout inside a Finalizer that does not implement
Database.AllowsCallouts.
Exercise
A Queueable job sends a callout and the server returns status 503. No exception is thrown and the Finalizer shows ParentJobResult.SUCCESS. Why, and where should you handle this case?
Show answer
Http.send returns normally for any HTTP response, so the job ends successfully from the platform's point of view. Handle the 503 inside execute by checking res.getStatusCode(). A 503 is often temporary, so you can enqueue a retry there with a retry counter.
Exercise
Why should System.attachFinalizer be the first statement in execute?
Show answer
The Finalizer only exists if the attach line runs. If an exception happens earlier in execute, a Finalizer attached later is never registered and cannot report the failure.