Sub topic 5
Checking status codes and reading error bodies
This chapter assumes you can write a basic Apex callout with Http, HttpRequest, and HttpResponse. It also assumes you know common HTTP status codes and understand that the 10-second default timeout can be changed. The previous chapter separated thrown exceptions from error responses. This chapter covers the second kind: what your code must do when the call completes and the server says it failed.
Why Apex will not check for you
Http.send returns normally for any response the server produces, including 404 and 503. It throws System.CalloutException only when no usable response arrives, for example on a timeout or a connection failure. If you skip the status check, your code treats an error page as data and fails later in a confusing place, often during JSON parsing.
Check the status code on every response before you read the body.
Grouping status codes
You do not need a branch for every code. Group them by what your code should do next.
| Range | Meaning | Typical action |
|---|---|---|
| 2xx | The request succeeded | Parse the body |
| 3xx | Redirect | Usually follow the `Location` header or fix the endpoint |
| 4xx | The request was wrong | Do not retry. Fix the data or credentials |
| 5xx | The server failed | Often worth retrying |
Some 4xx codes are exceptions to the "do not retry" rule. 408 (request timeout) and 429 (too many requests) describe temporary conditions. The next chapter builds the retry decision on this. Here, put the checks in small helper methods so every caller shares the same definition.
public with sharing class StatusCheck {
public static Boolean isSuccess(Integer statusCode) {
return statusCode >= 200 && statusCode < 300;
}
public static Boolean isRetryable(Integer statusCode) {
return statusCode == 408
|| statusCode == 429
|| (statusCode >= 500 && statusCode <= 599);
}
}Reading the error body
Most APIs explain a failure in the body. A 400 response might carry {"error":"invalid_sku","message":"SKU ABC is unknown"}. That text tells you whether to fix the data or give up, so capture it. Log it or put it in your exception message.
Two cautions apply.
- Error bodies are not always JSON. A gateway or load balancer may return an HTML page for a 502 or 503. Parse defensively, and fall back to a truncated raw string.
- Error bodies can contain sensitive values, such as echoed request data. Do not write full bodies to logs or records that many users can read.
The following method turns an error response into an exception with a useful, bounded message.
public with sharing class ResponseReader {
public class ApiException extends Exception {}
public static String readBody(HttpResponse res) {
String body = res.getBody();
return (body == null) ? '' : body;
}
public static String describeError(HttpResponse res) {
String body = readBody(res);
String detail = body.abbreviate(300);
try {
Object parsed = JSON.deserializeUntyped(body);
if (parsed instanceof Map<String, Object>) {
Map<String, Object> m = (Map<String, Object>) parsed;
if (m.get('message') != null) {
detail = String.valueOf(m.get('message')).abbreviate(300);
}
}
} catch (System.JSONException e) {
// Not JSON. Keep the truncated raw text.
}
return 'HTTP ' + res.getStatusCode() + ' ' + res.getStatus() + ': ' + detail;
}
public static String parseOrThrow(HttpResponse res) {
if (!StatusCheck.isSuccess(res.getStatusCode())) {
throw new ApiException(describeError(res));
}
return readBody(res);
}
}abbreviate(300) keeps the message short. getStatus() returns the reason phrase, such as Not Found, which is useful in logs.
How the pieces fit together
Common mistakes
- Checking only for
200. APIs also return 201 for created records and 204 for success with no body. Use the 2xx range. - Calling
JSON.deserializebefore the status check. - Treating every non-2xx response as retryable. A 400 will fail the same way every time.
- Reading
getBody()on a 204 and expecting content.
Exercise
A callout to an order API returns status 503 with an HTML body. Does Http.send throw an exception? What should your code do before it tries to parse the body?
Show answer
No. Http.send returns the response normally, because the server did answer. The code must check the status code first. A 503 is a server failure that is a candidate for retry, so it should not be parsed as JSON. If the body is logged, truncate it, since it is HTML and not structured error data.
Exercise
Why is statusCode == 200 a poor success check?
Show answer
Successful APIs also return other 2xx codes, such as 201 Created and 204 No Content. Checking the whole 200 to 299 range avoids treating those valid responses as failures.