Sub topic 8
Handling errors and failed calls
This chapter assumes you can write a basic callout with Http, HttpRequest and HttpResponse. It also assumes you know HTTP status code families and Apex exception handling. Here you will learn how a callout can fail, how to tell the failures apart, and how to turn them into predictable behavior in your own code.
Two kinds of failure
A callout can fail in two different ways. They look different in code, so you handle them differently.
- The call never completes. The platform could not reach the server, the connection timed out, or the endpoint is not authorized.
Http.send()throws aSystem.CalloutException. You never get anHttpResponse. - The call completes with an error status. The server answered with 4xx or 5xx.
Http.send()returns normally. Nothing is thrown. Your code must read the status code and decide what it means.
The second kind is the more common source of bugs. A callout that returns 404 or 500 does not raise an exception, so code that goes straight to res.getBody() will try to parse an error page as if it were data.
Checking the status code
Always test the status code before you use the body. Check for the specific code you expect, not just "anything below 300". A create call returns 201, and a delete often returns 204 with no body at all.
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());
}
}This method has a clear contract. It returns a body only on 200. For anything else it throws a custom TodoException that includes the code and the status text. The caller never receives an error page by accident.
Status code families
Group the codes by what the caller can do about them.
| Range | Meaning | Typical response in Apex |
|---|---|---|
| 2xx | Success | Parse the body (if there is one). |
| 3xx | Redirect | Apex does not follow every redirect for you. Read the `Location` header if you need it. |
| 400, 422 | Bad request or invalid data | Do not retry. Log the request and fix the payload. |
| 401, 403 | Not authenticated or not allowed | Do not retry blindly. Check the Named Credential and the external user's permissions. |
| 404 | Resource not found | Often a valid business outcome. Decide whether it is an error for this caller. |
| 429 | Too many requests | Retry later, and honor a `Retry-After` header if present. |
| 500, 502, 503, 504 | Server-side failure | Retry later with a limit, or queue the work. |
A 404 is a good example of why one rule does not fit every case. When you look up a record you may have just deleted, "not found" is an answer. When you call an endpoint that must exist, it is a configuration bug.
Catching CalloutException
System.CalloutException covers failures where no response arrived. Common causes are:
- Read timeout, with a message such as
Read timed out. - Unreachable host or failed connection.
- An endpoint that is not authorized, for example a missing Remote Site Setting. The message names the unauthorized endpoint.
- A malformed request, such as an invalid endpoint URL or a missing method.
- Too many callouts in one transaction, which raises a limit exception that you cannot catch (see below).
Catch it close to the callout, add context, and rethrow or return a result your caller understands.
public with sharing class SafeTodoService {
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.setTimeout(10000);
HttpResponse res;
try {
res = new Http().send(req);
} catch (CalloutException e) {
throw new TodoException('Callout failed for todo ' + todoId + ': ' + e.getMessage(), e);
}
Integer code = res.getStatusCode();
if (code == 200) {
return res.getBody();
}
if (code == 404) {
return null;
}
throw new TodoException('Todo service returned ' + code + ': ' + res.getStatus());
}
}Wrapping the exception as the cause keeps the original stack trace. The wrapped message tells a support engineer which record was involved.
The try block is deliberately narrow. It surrounds only send(). If you wrap status checks and JSON parsing in the same catch (CalloutException e), you may hide unrelated bugs behind a callout message.
Governor limit exceptions cannot be caught
Exceeding the callout limit raises a System.LimitException. This is not a normal exception. You cannot catch it, and the transaction ends. A catch (Exception e) will not save you.
// This does NOT prevent the transaction from ending:
try {
for (Integer i = 0; i < 200; i++) {
new Http().send(req);
}
} catch (Exception e) {
// Never reached for LimitException
}Prevent the problem by design. Check Limits.getCallouts() against Limits.getLimitCallouts() before looping, and batch or queue work when you are close to the limit. The limit rules themselves are covered in the chapter on callout limits.
Parse failures are a third source of errors
A 200 response can still contain a body you cannot use. The server may return HTML from a proxy, an empty body, or JSON with a different shape. JSON.deserialize throws a System.JSONException when the body does not match.
public with sharing class TodoParser {
public class Todo {
public Integer id;
public String title;
public Boolean completed;
}
public static Todo parse(String body) {
if (String.isBlank(body)) {
throw new IllegalArgumentException('Empty response body');
}
try {
return (Todo) JSON.deserialize(body, Todo.class);
} catch (JSONException e) {
throw new IllegalArgumentException('Response was not a valid todo: ' + e.getMessage(), e);
}
}
}Check Content-Type when a service is known to return mixed formats. A res.getHeader('Content-Type') that starts with text/html on an API call usually means a gateway error page.
Retrying safely
Some failures are temporary. A 503 or a timeout may succeed on the next attempt. Apex has no built-in retry, and retrying inside the same transaction has costs.
- Every attempt counts against the callout limit and the total callout time.
- Apex has no
sleep. You cannot wait between attempts in synchronous code. - Retrying a non-idempotent request such as
POSTcan create duplicates if the first request actually succeeded and only the response was lost.
For these reasons, retry by re-enqueueing a Queueable job with a counter, and cap the number of attempts.
public class RetryingTodoJob implements Queueable, Database.AllowsCallouts {
private static final Integer MAX_ATTEMPTS = 3;
private Integer todoId;
private Integer attempt;
public RetryingTodoJob(Integer todoId, Integer attempt) {
this.todoId = todoId;
this.attempt = attempt;
}
public void execute(QueueableContext context) {
try {
String body = SafeTodoService.fetchTodo(todoId);
System.debug('Fetched: ' + body);
} catch (SafeTodoService.TodoException e) {
if (attempt < MAX_ATTEMPTS) {
System.enqueueJob(new RetryingTodoJob(todoId, attempt + 1));
} else {
System.debug(LoggingLevel.ERROR, 'Giving up on todo ' + todoId + ': ' + e.getMessage());
}
}
}
}This job retries on every TodoException, including 400 responses that will never succeed. In production, define separate exception types, or carry the status code, so that only retryable failures (timeouts, 429, 5xx) are re-enqueued.
Logging without leaking data
When a callout fails, you need enough detail to diagnose it. Log the method, the endpoint path, the status code, and a record identifier. Do not log credentials, tokens, or full request bodies that contain personal data.
- Named Credentials keep secrets out of your code, so they will not appear in logs you write. Avoid copying headers into log messages.
- Truncate large bodies.
res.getBody().abbreviate(500)keeps log lines manageable. - For failures that need follow-up, write to a custom object or publish a platform event. Debug logs expire and are not a record of failures.
Failures after a successful callout
Callout errors are not the only things that can go wrong. If your code makes a callout and then performs DML, the DML can fail after the external system has already changed state. The reverse order has its own rule: a callout after uncommitted DML in the same transaction throws a CalloutException about uncommitted work pending. Plan the order of operations, and treat the external call as the step that cannot be rolled back.
Common mistakes
- Using
res.getBody()without checkinggetStatusCode(). - Treating any status below 300 as success when the code needs a specific value.
- Catching
Exceptionaround an entire method, which hides logic bugs. - Expecting
catchto handleLimitException. - Retrying all failures, including
400and401. - Swallowing the exception and returning an empty string, so the caller cannot tell failure from "no data".
Exercise
A callout to an external API returns HTTP 503. Your code is wrapped in try { ... } catch (CalloutException e) { ... }. Does the catch block run, and what should your code do instead?
Show answer
The catch block does not run. A 503 is a completed call, so send() returns an HttpResponse and throws nothing. The code must read res.getStatusCode(), recognize 503 as a temporary server failure, and either throw its own exception or queue a limited retry.
Exercise
Why is it a problem to retry a failed POST callout three times in a loop inside one synchronous transaction?
Show answer
Each attempt uses callout limit and callout time, Apex cannot wait between attempts, and the POST may have succeeded on the server with only the response lost, which creates duplicates. Re-enqueue a Queueable with an attempt counter and use an idempotency key or a lookup before retrying.