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 the common HTTP status code classes and the difference between synchronous and asynchronous Apex. By the end you will be able to tell the two failure channels apart, handle each in the right place, and return one result type that later retry code can rely on.
Why one try/catch is not enough
Many first callouts look like this:
try {
HttpResponse res = new Http().send(req);
return res.getBody();
} catch (Exception e) {
// handle errors
}This code assumes every failure shows up as an exception. In Apex it does not. A callout can fail in two different ways, and they use different channels:
- A thrown exception. The request did not complete, so no
HttpResponseexists. - An error response. The server answered, and
sendreturned normally, but the status code says something went wrong.
The catch block above sees the first kind only. A 500 Internal Server Error returns an HttpResponse with a body, so the method returns the body of an error page as if it were data. This is the most common bug in callout code.
Channel 1: exceptions from send
Http.send throws System.CalloutException when the HTTP exchange cannot finish. Typical causes:
- The read timed out (the message is usually
Read timed out). - The connection could not be made, for example because the host name does not resolve or the connection was reset.
- The TLS handshake failed.
- The endpoint is not authorized. The callout targets a URL that has no Remote Site Setting or Named Credential, and the message starts with
Unauthorized endpoint. - You made a callout while the transaction had uncommitted DML. The message is
You have uncommitted work pending. Please commit or rollback before calling out. The chapter on callouts, DML, and triggers covers this in detail. - A test ran a callout without a mock set.
Some of these are transient, like a timeout. Others are bugs in your configuration or code, like an unauthorized endpoint. All of them arrive as the same exception type, so the message text is the only built-in clue. Do not parse that text to make decisions. Treat a CalloutException as "transport failure" and decide what to do from the context of the call.
A CalloutException also leaves one fact open: you do not know whether the server received the request. A read timeout means the request was sent and the response did not arrive in time. The server may have finished the work after you gave up. This ambiguity is why the chapter on idempotency matters for retries.
Exceptions that are not CalloutException
Other exceptions can occur around a callout, and they are different problems:
| Exception | Typical cause | Catchable? |
|---|---|---|
| `System.CalloutException` | Timeout, connection failure, unauthorized endpoint, uncommitted work | Yes |
| `System.LimitException` | More than the allowed number of callouts, or too much total callout time | No |
| `System.JSONException` | Parsing a body that is not valid JSON, for example an HTML error page | Yes |
| `System.NullPointerException` | Reading a field from a parsed body that is missing | Yes |
A LimitException cannot be caught. Your try/catch will not save the transaction, so you must count callouts and stay under the limit by design. The next chapters return to limits.
The JSONException row is closely related to this chapter. It usually comes from the second failure channel, as the next section shows.
Channel 2: error responses
When the server answers, Http.send returns an HttpResponse whatever the status code is. Apex does not throw on 404, 429, or 503. You must inspect the response yourself:
HttpResponse res = new Http().send(req);
Integer code = res.getStatusCode(); // 200, 404, 503, ...
String status = res.getStatus(); // "OK", "Not Found", ...
String body = res.getBody(); // may be JSON, HTML, plain text, or emptyThree details cause trouble in practice.
Redirects are not followed for you. A 301 or 302 is returned as a response. The new location is in the Location header, which you can read with res.getHeader('Location'). If you treat any non-error code as success, you will parse the empty body of a redirect. Check for the 2xx range explicitly instead of testing code < 400.
Error bodies do not match your success format. A successful call may return JSON that matches your wrapper class. A failed call may return a different JSON shape, an HTML page from a gateway, or nothing. Parse the body only after you have confirmed success. When the call failed, keep the raw body (shortened) for diagnostics.
Gateways produce errors your API never sends. A load balancer in front of the service may return 502 or 504 with an HTML body even though the service itself always returns JSON. A 504 Gateway Timeout is a server-side timeout reported as a normal response. It looks different from your own client-side timeout, which is an exception, but it means the same kind of thing: the work may or may not have happened.
The following table summarizes the two channels side by side.
| Row | Thrown exception | Error response |
|---|---|---|
| How it appears | `System.CalloutException` from `send` | Normal return with `getStatusCode()` of 400 to 599 |
| Is there a response? | No | Yes, with status, headers, and body |
| Did the server process the request? | Unknown | Usually known from the status code, but not for 502, 503, or 504 |
| Where to detect it | `catch` block | `if` check on the status code |
| Example | `Read timed out` | `429 Too Many Requests` |
One result type for both channels
The goal is to stop the two channels from leaking into the rest of your code. A common design is a small result class that the callout method always returns. Callers then deal with one shape and never need to know which channel a failure used.
public with sharing class CalloutOutcome {
public enum Kind { SUCCESS, HTTP_ERROR, TRANSPORT_FAILURE }
public Kind kind { get; private set; }
public Integer statusCode { get; private set; }
public String body { get; private set; }
public String errorMessage { get; private set; }
private CalloutOutcome() {}
public static CalloutOutcome fromResponse(HttpResponse res) {
CalloutOutcome o = new CalloutOutcome();
o.statusCode = res.getStatusCode();
o.body = res.getBody();
if (o.statusCode >= 200 && o.statusCode < 300) {
o.kind = Kind.SUCCESS;
} else {
o.kind = Kind.HTTP_ERROR;
String snippet = String.isBlank(o.body) ? '' : o.body.abbreviate(500);
o.errorMessage = 'HTTP ' + o.statusCode + ' ' + res.getStatus() + ' ' + snippet;
}
return o;
}
public static CalloutOutcome transportFailure(String message) {
CalloutOutcome o = new CalloutOutcome();
o.kind = Kind.TRANSPORT_FAILURE;
o.errorMessage = message;
return o;
}
public Boolean isSuccess() {
return kind == Kind.SUCCESS;
}
}The callout method turns both channels into this one type:
public with sharing class OrderGateway {
public static CalloutOutcome get(String path) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API' + path);
req.setMethod('GET');
req.setTimeout(30000);
try {
HttpResponse res = new Http().send(req);
return CalloutOutcome.fromResponse(res);
} catch (System.CalloutException e) {
return CalloutOutcome.transportFailure(e.getMessage());
}
}
}A caller can now write:
CalloutOutcome outcome = OrderGateway.get('/orders/1001');
if (outcome.isSuccess()) {
Map<String, Object> order =
(Map<String, Object>) JSON.deserializeUntyped(outcome.body);
System.debug('Order status: ' + order.get('status'));
} else {
System.debug(LoggingLevel.ERROR, 'Callout failed: ' + outcome.errorMessage);
}The JSON is parsed only inside the success branch. An HTML error page never reaches JSON.deserializeUntyped.
Keeping the channels distinct
When you wrap failures, keep what each channel tells you:
- For a transport failure, record the exception message and the exception's type name. You have no status code, so do not invent one such as
0and then treat it like an HTTP status. - For an HTTP error, record the status code and a shortened body. Do not log whole bodies, since they can hold personal data. Do not log request headers, since they can hold credentials.
- Never convert an error response into a
CalloutExceptionjust to reuse acatchblock. That throws away the status code you need to decide whether a retry is useful.
In the code above, abbreviate(500) limits the body stored in the message. Pick a limit that fits wherever you store the message, for example a text field on a log record.
Common mistakes
- Catching
Exceptionand assuming success otherwise. If thetrybody returns the body of any response, an error page looks like data. - Testing
statusCode == 200. Many APIs return201,202, or204on success. Use the 2xx range. - Testing
statusCode < 400. This treats3xxredirects as success. - Parsing before checking. Deserializing a body first and checking the status second turns a clean
503into a confusingJSONException. - Treating every
CalloutExceptionas "the server did nothing". After a timeout, the server may have completed the request. - Expecting to catch limit errors.
LimitExceptionends the transaction no matter what yourcatchblocks do.
Exercise
A callout method returns res.getBody() inside a try block and has catch (System.CalloutException e) that logs the error. The server returns 503 Service Unavailable with an HTML maintenance page. What happens in the code, and what is the minimal fix?
Show answer
Http.send does not throw on a 503, so the catch block never runs. The method returns the HTML maintenance page as if it were a successful body, and any later JSON parsing fails with a JSONException. The fix is to read res.getStatusCode() after send returns and treat anything outside 200 to 299 as an error, returning or raising a failure that includes the status code and a shortened body.
Exercise
A POST request to create an order throws CalloutException: Read timed out. A teammate says the order was definitely not created, so retrying is safe. Is that correct? Give your reasoning.
Show answer
No. A read timeout means the request was sent and the client stopped waiting for the response. The server may have processed it and created the order. A plain retry could create a duplicate. A retry is safe only if the operation is idempotent, for example because the request carries an idempotency key that lets the server recognize the repeat.