Sub topic 2
Checking Status Codes and Reading Error Bodies
Assume you know basic Apex classes, HTTP methods, and governor limits. An Apex callout can fail in two different ways: Http.send can throw a CalloutException, or it can return an HttpResponse with an error status.
Checking Status Codes and Reading Error Bodies
A response with status 400, 401, 404, 429, or 500 is still a normal response to Apex. Check the status code yourself, then read the body for diagnostics.
public with sharing class ResponseHandler {
public class ApiException extends Exception {}
public static void handle(HttpResponse response) {
Integer code = response.getStatusCode();
String body = response.getBody();
if (code >= 200 && code < 300) {
return;
}
if (code == 408 || code == 429 || code >= 500) {
throw new ApiException('Retryable HTTP error ' + code + ': ' + body);
}
throw new ApiException('Permanent HTTP error ' + code + ': ' + body);
}
}Do not expose an untrusted response body directly to users. Log enough information to investigate, but remove tokens, personal data, and other secrets.
Deciding What Is Worth Retrying
Retry temporary failures, not invalid requests. Common retryable cases include 408 Request Timeout, 429 Too Many Requests, and most 5xx responses. A 400 or 401 usually requires correcting the request or credentials.
Use a bounded policy with increasing delays. Backoff reduces pressure on an overloaded service.
Callouts, DML, and Triggers
A callout cannot follow pending uncommitted DML in the same transaction. Move the callout before DML, or separate the work into asynchronous transactions. Triggers should enqueue a Queueable job or use another supported asynchronous mechanism for callouts.
Making Repeated Requests Safe
A retry can submit a request twice if the first response is lost. For a state-changing request such as POST, send an idempotency key, which is a unique request identifier. The remote service must store that key and return the original result when it sees the same key again. Prefer naturally repeatable operations, such as GET, when appropriate.
Exercise
Should a 400 response normally be retried?
Show answer
No. It usually describes a permanent request error. Fix the request or record the failure for review.