Sub topic 4
Two kinds of failure: exceptions and error responses
This chapter assumes you can write a basic callout with Http, HttpRequest, and HttpResponse. It also assumes you know HTTP status code families and the difference between synchronous and asynchronous Apex. Here you will learn that a callout can fail in two different ways, and that each needs its own handling.
The two failure channels
A callout can go wrong in two ways.
- Apex throws an exception. The request did not complete. Examples are a read timeout, a failed connection, or an unreachable host. Apex throws a
System.CalloutException. - The server answers with an error. The request completed and the server replied with a 4xx or 5xx status code.
Http.sendreturns a normalHttpResponse. It does not throw.
The second case catches many developers. Code that only has a try/catch around send will treat a 500 response as a success, because no exception occurred.
What each channel tells you
The two channels carry different information, so they lead to different decisions.
| Aspect | Exception | Error response |
|---|---|---|
| How you see it | `catch (System.CalloutException e)` | `res.getStatusCode()` |
| Did the server answer? | No | Yes |
| Did the server process the request? | Unknown | Usually no, but not guaranteed |
| Typical causes | Timeout, connection failure | Bad input, auth failure, server fault |
| Detail available | `e.getMessage()` | Status code, headers, body |
The most important row is the third one. After a timeout, you do not know whether the server received and processed the request. The server may have finished the work after your client gave up waiting. This matters when you decide whether to repeat a request, and a later chapter on idempotency covers it.
Handling both channels in one place
Put both checks in one method so callers see one consistent result. The method below wraps the exception in a domain-specific exception. It also turns a non-2xx status into the same exception type.
public with sharing class OrderApiClient {
public class ApiException extends Exception {
public Integer statusCode;
}
public static HttpResponse send(String path) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API' + path);
req.setMethod('GET');
req.setTimeout(30000); // milliseconds; the default is 10000
HttpResponse res;
try {
res = new Http().send(req);
} catch (System.CalloutException e) {
// Channel 1: thrown for timeouts and connection failures
throw new ApiException('Callout failed: ' + e.getMessage(), e);
}
// Channel 2: the call completed, so inspect the status code
if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
ApiException ex = new ApiException(
'Error response: ' + res.getStatusCode()
);
ex.statusCode = res.getStatusCode();
throw ex;
}
return res;
}
}Note what the statusCode field does. For a thrown CalloutException, it stays null. For an error response, it holds the code. A caller can check statusCode == null to tell "no answer" from "answered with an error". That distinction feeds the retry decisions later in this tutorial.
Common mistakes
- Catching only exceptions. A 503 slips through as if it were a success, and your code then tries to parse an error page as JSON.
- Catching
Exceptionbroadly. This hides programming errors such as aNullPointerExceptionbehind a message about the callout. - Treating all failures alike. A 400 means the request itself is wrong, so repeating it cannot help. A timeout or a 503 may succeed on a second attempt.
- Losing the original cause. Pass the caught exception as the second argument, as shown above, so the stack trace survives.
Check your understanding
Exercise
A callout to an external API returns a response with status code 503. Your code wraps new Http().send(req) in try { ... } catch (System.CalloutException e) { ... } and has no other checks. What happens, and how do you fix it?
Show answer
The catch block never runs, because Apex does not throw for a 503. send returns an HttpResponse normally, and the code continues as if the call succeeded. To fix it, read res.getStatusCode() after send returns and treat any code outside 200 to 299 as a failure, for example by throwing a domain-specific exception that carries the status code.
Exercise
A callout times out. Can you safely assume the server did not create the order you posted? Why does this matter?
Show answer
No. A timeout means the client stopped waiting. The server may have received the request and finished processing it afterward. Repeating a non-idempotent request, such as a POST that creates an order, could create a duplicate. This is why repeated requests need idempotency keys.