Sub topic 5
Checking Status Codes and Reading Error Bodies
The previous chapter separated two kinds of callout failure. Http.send can throw a CalloutException, or it can return an HttpResponse that carries an error status. This chapter covers the second kind. You will learn to check status codes, read the error body safely, and turn the result into a decision your retry logic can use.
This chapter assumes you can write a basic callout with Http, HttpRequest, and HttpResponse. It also assumes you know the HTTP status code families and have written Apex try/catch blocks.
Why a response is not automatically a success
Http.send throws only when no usable HTTP response comes back. Timeouts, DNS failures, and refused connections fall in that group. If the server answers with 404, 429, or 503, Apex treats the call as completed. You get an HttpResponse object and no exception.
A common bug is code like this:
HttpResponse res = new Http().send(req);
Order__c o = (Order__c) JSON.deserialize(res.getBody(), Order__c.class);If the server returned a 500 with an error body, this code tries to parse the error as an order. It then either throws a confusing JSONException or, worse, quietly builds an object with empty fields. Always check the status before you use the body.
What an HttpResponse gives you
| Method | Returns | Notes |
|---|---|---|
| `getStatusCode()` | `Integer` | The number to branch on, such as 200 or 503. |
| `getStatus()` | `String` | The reason phrase, such as `Service Unavailable`. Useful in messages, but do not branch on it. Servers can change the wording. |
| `getBody()` | `String` | The body decoded as text. It may be empty. |
| `getBodyAsBlob()` | `Blob` | Use this for binary content such as files. |
| `getHeader(name)` | `String` | Returns `null` if the header is absent. |
Branch on the numeric code. The reason phrase is free text and varies between servers.
Checking the status
Treat the whole 2xx range as success, not only 200. A POST often returns 201 Created. A DELETE often returns 204 No Content, which has no body, so parsing the body would fail.
public static Boolean isSuccess(Integer statusCode) {
return statusCode >= 200 && statusCode < 300;
}For failures, the code families tell you where the fault lies.
| Range | Meaning | Typical handling |
|---|---|---|
| 2xx | Success | Parse the body only if the status says there is one (not 204). |
| 3xx | Redirection | Treat as unexpected unless your integration documents it. Log the `Location` header. |
| 4xx | The request was wrong | Usually permanent. Fix the request. Do not retry blindly. |
| 408, 429 | Timeout or rate limit | Transient. Retry after a delay. |
| 5xx | The server failed | Often transient. Retry with a cap. |
The next chapter builds the full retry decision. For now, notice that the status code alone is usually enough to make a first split.
Reading the error body
An error response usually has a body that explains the problem. APIs differ in format, so write the reading code defensively. Three problems come up often:
- The body is empty, as with many 401, 403, and 5xx responses.
- The body is JSON, but the field holding the message has a different name in each API (
message,error,error_description). - The body is not JSON at all. A gateway or load balancer in front of the real API may return an HTML page on 502 or 503.
Do not assume JSON.deserializeUntyped will succeed on an error body. Check the Content-Type header, parse inside a try/catch, and fall back to a truncated raw string.
public with sharing class CalloutResponseHandler {
public class ApiException extends Exception {
public Integer statusCode;
}
private static final Integer MAX_MESSAGE_CHARS = 500;
public static String extractErrorMessage(HttpResponse res) {
String body = res.getBody();
if (String.isBlank(body)) {
return res.getStatus();
}
String contentType = res.getHeader('Content-Type');
if (contentType != null && contentType.containsIgnoreCase('json')) {
try {
Object parsed = JSON.deserializeUntyped(body);
if (parsed instanceof Map<String, Object>) {
Map<String, Object> fields = (Map<String, Object>) parsed;
for (String key : new List<String>{ 'message', 'error_description', 'error' }) {
Object value = fields.get(key);
if (value instanceof String) {
return (String) value;
}
}
}
} catch (JSONException e) {
// Declared JSON but malformed. Fall through to the raw text.
}
}
return body.abbreviate(MAX_MESSAGE_CHARS);
}
public static HttpResponse requireSuccess(HttpResponse res) {
Integer code = res.getStatusCode();
if (code >= 200 && code < 300) {
return res;
}
ApiException ex = new ApiException(
'HTTP ' + code + ': ' + extractErrorMessage(res)
);
ex.statusCode = code;
throw ex;
}
}Several choices in this code matter.
requireSuccessthrows a custom exception that carries the status code. Callers can catch one exception type and still readstatusCodeto decide whether to retry. This puts both failure kinds on one path. A caller handles theApiExceptionthrown here and the wrappedCalloutExceptionfrom the earlier chapter in the same place.- The message is capped with
abbreviate. Error bodies can be large. HTML error pages can run to thousands of characters. Capping them protects debug logs, custom object text fields, and the heap. - The
JSONExceptioncatch is deliberate and not empty by accident. A server that mislabels its content type should not turn a 500 into an unrelated parsing error.
Be careful what you log
Error bodies sometimes echo your request back, including tokens, email addresses, or other personal data. Before you store a body in a custom object or send it to a log, decide whether it is safe to keep. Truncating helps. Redacting known sensitive fields is better when the API is known to echo them. Never log request headers such as Authorization.
Using headers that guide a retry
Two response headers are worth reading on failure.
Retry-After appears on 429 and 503 responses. It tells you how long to wait. Its value is either a number of seconds or an HTTP date. Parse only the numeric form and ignore anything else.
public static Integer retryAfterSeconds(HttpResponse res) {
String raw = res.getHeader('Retry-After');
if (raw != null && raw.trim().isNumeric()) {
return Integer.valueOf(raw.trim());
}
return null; // Absent or an HTTP date: use your own backoff.
}A returned null means "no guidance", so your backoff policy takes over. When a value is present, treat it as a minimum wait. Waiting less than the server asked for usually earns another 429.
A request ID header (often X-Request-Id or similar) is useful for support. Record it with the failure so the API owner can find the matching server-side log. The header name varies by provider, so check the API documentation.
Special cases worth handling
- 401 Unauthorized. With a Named Credential, token refresh is normally handled for you. A 401 that still appears often means the credential is misconfigured or revoked. Retrying will not fix it, so treat it as permanent and alert someone.
- 409 Conflict. This often means the resource already exists. If the earlier attempt actually succeeded, 409 can be the proof of it. Idempotency, covered later in this tutorial, is the clean way to handle this.
- 200 with an error inside. Some APIs return 200 and put
{"success": false}in the body. The status check does not catch this. Read the API contract and validate the body for those endpoints. - Empty 2xx bodies. For 204, skip parsing. Guard with
String.isNotBlank(res.getBody())before you deserialize.
Testing the error path
You can verify the handler without a real endpoint. A mock that returns a 503 with a JSON body exercises the status check, the content-type branch, and the message extraction together.
@IsTest
private class CalloutResponseHandlerTest {
private class ServiceUnavailableMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(503);
res.setStatus('Service Unavailable');
res.setHeader('Content-Type', 'application/json');
res.setHeader('Retry-After', '30');
res.setBody('{"message":"Try again shortly"}');
return res;
}
}
@IsTest
static void errorResponseBecomesApiExceptionWithStatus() {
Test.setMock(HttpCalloutMock.class, new ServiceUnavailableMock());
HttpRequest req = new HttpRequest();
req.setEndpoint('https://example.com/orders');
req.setMethod('GET');
Test.startTest();
HttpResponse res = new Http().send(req);
Test.stopTest();
Assert.areEqual(30, CalloutResponseHandler.retryAfterSeconds(res));
try {
CalloutResponseHandler.requireSuccess(res);
Assert.fail('Expected an ApiException');
} catch (CalloutResponseHandler.ApiException e) {
Assert.areEqual(503, e.statusCode);
Assert.isTrue(e.getMessage().contains('Try again shortly'));
}
}
}The mock returns a response, not an exception, which matches how a real 503 behaves. The Assert.fail call inside the try is caught only by ApiException, so it fails the test if requireSuccess does not throw. Note that Assert.fail throws an AssertException, which the catch clause does not match, so the failure propagates as intended.
Common mistakes
- Checking only
== 200. This rejects valid 201 and 204 responses. - Parsing before checking. Always check the status first.
- Branching on
getStatus(). Use the number. - Storing whole error bodies. Cap their length and consider what they contain.
- Retrying every 4xx. Most 4xx responses mean the request itself is wrong, and repeating it gives the same answer.
Exercise
A callout to a billing API returns status 502 with a body that is an HTML page, and the Content-Type header is text/html. Using the handler in this chapter, what message does extractErrorMessage return, and why does the code not throw a JSONException?
Show answer
It returns the raw body truncated to 500 characters. The Content-Type does not contain "json", so the JSON parsing branch is skipped and JSON.deserializeUntyped is never called. Execution reaches the final line, body.abbreviate(MAXMESSAGECHARS). Even if the header had falsely claimed JSON, the JSONException would be caught and the same fallback would apply.
Exercise
An endpoint returns 204 No Content on success. Your code calls JSON.deserialize(res.getBody(), Order__c.class) after a check of statusCode == 200. What goes wrong, and how do you fix it?
Show answer
Two things go wrong. The check statusCode == 200 treats the valid 204 as a failure. Also, if the check passed, the body would be empty and deserialization would throw. Fix it by using the 2xx range check (statusCode >= 200 && statusCode < 300) and parsing only when String.isNotBlank(res.getBody()).