Sub topic 8
Handling errors and failed calls
This chapter assumes you can write a basic Apex callout with Http, HttpRequest and HttpResponse, and that you know HTTP status code families. A callout can fail in two different ways, and each needs different handling.
Two kinds of failure
A callout can fail before any response arrives, or it can succeed at the network level and return an error status.
- Transport failures throw a
System.CalloutException. Examples are a timeout, a DNS failure, an unauthorized endpoint, or a connection reset. You never get anHttpResponse. - HTTP failures return normally. The server answers with a 4xx or 5xx status, and
send()does not throw. If you skip the status check, you may parse an error page as if it were data.
Check the status before reading the body
Always test the status code first. Use the exact codes the API documents, because 200, 201 and 204 all mean success but carry different bodies.
public with sharing class TodoService {
public class TodoException extends Exception {}
public static String fetchTodo(Integer todoId) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos/' + todoId);
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setTimeout(20000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
return res.getBody();
}
throw new TodoException('Unexpected status ' + res.getStatusCode() + ': ' + res.getStatus());
}
}The method returns the body only on 200. Any other status becomes a custom exception that carries the code and the reason phrase.
Catch CalloutException
Wrap send() in a try/catch when the caller should keep running after a transport failure.
public with sharing class SafeTodoService {
public class Result {
public Boolean ok;
public String body;
public String error;
}
public static Result fetch(Integer todoId) {
Result r = new Result();
try {
r.body = TodoService.fetchTodo(todoId);
r.ok = true;
} catch (CalloutException e) {
r.ok = false;
r.error = 'Network problem: ' + e.getMessage();
} catch (TodoService.TodoException e) {
r.ok = false;
r.error = 'Service problem: ' + e.getMessage();
}
return r;
}
}The two catch blocks keep the cases apart. A timeout (CalloutException) is often worth retrying. A 404 is not.
Decide what each status means
| Status | Meaning | Typical action |
|---|---|---|
| 400, 422 | Your payload is wrong | Log the body, fix the request, do not retry |
| 401, 403 | Credentials missing or not permitted | Check the Named Credential and the user's permissions |
| 404 | Resource does not exist | Treat as "not found", not as a crash |
| 429 | Rate limited | Retry later |
| 500, 502, 503 | Server problem | Retry later, then give up |
Retry carefully
Apex has no sleep, so you cannot wait between attempts inside one transaction. A tight retry loop also burns your callout limit of 100 per transaction. Retry by re-enqueueing a Queueable job, with a counter so it stops.
public class RetryTodoJob implements Queueable, Database.AllowsCallouts {
private Integer todoId;
private Integer attempt;
public RetryTodoJob(Integer todoId, Integer attempt) {
this.todoId = todoId;
this.attempt = attempt;
}
public void execute(QueueableContext context) {
try {
TodoService.fetchTodo(todoId);
} catch (Exception e) {
if (attempt < 3) {
System.enqueueJob(new RetryTodoJob(todoId, attempt + 1));
} else {
System.debug(LoggingLevel.ERROR, 'Giving up on todo ' + todoId + ': ' + e.getMessage());
}
}
}
}Common mistakes
- Reading
getBody()without checking the status. - Catching a bare
Exceptionand hiding the cause. - Retrying
4xxerrors, which fail the same way each time. - Putting sensitive data in exception messages that reach users.
Exercise
A callout to an API returns status 503. Does send() throw a CalloutException? What should your code do?
Show answer
No. send() returns normally with an HttpResponse whose status code is 503, so a catch (CalloutException) block never runs. Check getStatusCode(), treat 5xx as a possible temporary server problem, and retry a limited number of times through a Queueable job before giving up and logging the failure.
Exercise
Why is a try/catch around send() alone not enough to handle a 404?
Show answer
A 404 is a normal HTTP response, so no exception is thrown. You must read the status code and branch on it yourself.