Sub topic 13
Troubleshooting common errors
This chapter assumes you have already built the Weather_API setup from the earlier chapters. That means an External Credential with a principal, a Named Credential, a permission set, and an Apex class that uses a callout: endpoint. It also assumes you can read a debug log and know the usual HTTP status code classes. The goal is to find which layer is failing without guessing.
Work from the outside in
A callout passes through several layers. Each layer fails in its own way, and the error text usually shows which one broke.
Two questions split most problems. First, did Salesforce get a response at all? If Apex throws a CalloutException before an HTTP status exists, the problem is in Salesforce (configuration, access or transaction rules). If you get a status code, the request left Salesforce and the problem is in the request content or in the service.
Make failures visible
Log the status, the status text and a short slice of the body. Do not log request headers or anything that could contain a secret. The endpoint is safe to log because it still reads callout:Weather_API/..., not the resolved URL.
public with sharing class CalloutDiagnostics {
public static HttpResponse send(HttpRequest req) {
try {
HttpResponse res = new Http().send(req);
if (res.getStatusCode() >= 400) {
String body = res.getBody() == null ? '' : res.getBody().abbreviate(500);
System.debug(LoggingLevel.WARN, 'Callout to ' + req.getEndpoint()
+ ' returned ' + res.getStatusCode() + ' ' + res.getStatus() + ': ' + body);
}
return res;
} catch (CalloutException e) {
System.debug(LoggingLevel.ERROR, 'Callout failed before a response: ' + e.getMessage());
throw e;
}
}
}Response bodies can hold personal data, so keep the log level and retention in mind before you use this in production. To see the output, add a trace flag for the running user with the Callout and Apex Code categories at a detailed level. Then reproduce the failure.
Errors raised before a response
Unauthorized endpoint
The message looks like Unauthorized endpoint, please check Setup->Security->Remote site settings. It means Salesforce treated the endpoint as a plain URL and found no Remote Site Setting for it. Common causes:
- The endpoint does not start with
callout:. A literalhttps://...URL needs a Remote Site Setting. Switch to the Named Credential syntax instead. - The name after
callout:has a typo. Names are the API names (Weather_API), not the labels. - The Named Credential exists in another org or sandbox but was never deployed to this one.
The user cannot use the credential
A Named Credential that uses the new model does nothing for a user whose permission sets lack access to the External Credential principal. The exact wording varies by release. It usually says that the user has no access to the credential or principal. Check these in order:
- Open the permission set and confirm that External Credential Principal Access lists the right External Credential and principal.
- Confirm the permission set is assigned to the user whose context runs the code. For a trigger, Flow or Apex run by a person, that is the person. For scheduled Apex, it is the user who scheduled it. For an integration user, assign the permission set to that user.
- If you changed access recently, run the code again in a new transaction. Do not trust an old debug log.
Giving a user "Modify All Data" or the System Administrator profile does not substitute for principal access. Administrators need the permission set too.
A per user principal that has not authenticated
With a per user principal, each person must authenticate to the external system once. If a user has not done that, the callout fails with a message about missing authentication. The fix is not in Setup. The user opens their own settings, finds External Credentials (named Authentication Settings for External Systems in some releases), and authenticates. Also verify that the permission set grants access to the per user principal, because the authentication option does not appear without it.
A callout run by a user who has never authenticated will fail even if it works for you. This is the main reason a per user setup passes the developer's test and fails for the first real users.
Transaction rules
These errors come from Apex, not from the credential setup.
| Message or symptom | Cause | Fix |
|---|---|---|
| `You have uncommitted work pending. Please commit or rollback before calling out` | DML ran earlier in the same transaction. | Make the callout first, or move it to a Queueable. |
| `Callout from triggers are currently not supported` | A synchronous callout ran in trigger context. | Hand off to `@future(callout=true)` or a Queueable that implements `Database.AllowsCallouts`. |
| `Too many callouts: 101` | The limit is 100 callouts per transaction. | Reduce the callouts, or split the work across transactions. |
| `Read timed out` | The service took longer than the timeout (10 seconds by default). | Call `req.setTimeout(30000)` for a slower service. The maximum is 120000 ms. |
| `Methods defined as TestMethod do not support Web service callouts` | A test made a real callout. | Add `Test.setMock`. |
A Queueable that runs a callout looks like this.
public with sharing class ForecastJob implements Queueable, Database.AllowsCallouts {
private String city;
public ForecastJob(String city) {
this.city = city;
}
public void execute(QueueableContext ctx) {
String body = WeatherService.getForecast(city);
System.debug('Forecast length: ' + body.length());
}
}Start it with System.enqueueJob(new ForecastJob('Oslo'));. The job runs in its own transaction, so earlier DML has already committed.
Errors that arrive with a status code
When the service answers, the status code tells you which side to examine.
401 Unauthorized
The request reached the service but the credential was rejected. For an API key setup, check these:
- The authentication parameter name matches the formula exactly.
{!$Credential.Weather_EC.ApiKey}fails if the parameter is namedAPIKeyor the External Credential is named differently. - The secret was entered into the principal (not only defined as a parameter) and has no trailing space.
- The header name is the one the service expects.
X-Api-KeyandX-API-KEYare equivalent in HTTP, butAuthorizationandX-Api-Keyare not interchangeable. - The permission set grants the principal that actually holds the secret.
For OAuth, a 401 often means the access token expired and could not be refreshed. Re-authenticate the principal. Also check that the scopes requested in the authentication provider match what the API needs.
403 Forbidden
The service accepted the credential but refuses the action. Salesforce is not at fault. Check the account or key on the provider's side: its scopes, IP allow list, or plan limits. If the provider restricts by IP address, remember that Salesforce callouts come from a shared range of addresses.
404 Not Found
Salesforce builds the final URL by appending what follows callout:Weather_API to the Named Credential URL. With the URL https://api.example.com/v1, the endpoint callout:Weather_API/forecast?city=Oslo becomes https://api.example.com/v1/forecast?city=Oslo. Three mistakes recur:
- Writing the path twice, once in the Named Credential and again in Apex.
- Omitting the leading
/in the Apex path, which joins the segments incorrectly. - Leaving a trailing slash in the Named Credential URL and then adding
/in Apex, which produces//.
Pick one place for the base path and keep it consistent. Query values should go through EncodingUtil.urlEncode, as the earlier WeatherService does.
5xx and redirects
A 500, 502 or 503 comes from the service. Retry later, ideally with a limit, and report it to the provider if it persists. A 301 or 302 means the service moved. Apex does not follow redirects to a different host with your credentials automatically in every case, so update the Named Credential URL instead of relying on a redirect.
Test failures
If a test fails with the "do not support Web service callouts" message, the mock was not registered before the call. Call Test.setMock(HttpCalloutMock.class, ...) before the code under test. If the mock's assertions fail, remember that the mock sees the endpoint you set, still starting with callout:, not the resolved URL. A test that passes does not prove the Setup configuration is right. The mock bypasses the Named Credential, the principal and the permission set completely. Verify those once in a sandbox with a real call.
A short diagnostic routine
- Reproduce the failure as the affected user, not as yourself.
- Read the exception text and decide: no response, or a response with a status.
- For no response, check the
callout:name, then principal access in the permission set, then per user authentication, then transaction rules. - For a status, compare the final URL you expect with the Named Credential URL plus your path, then check the header formula and the secret.
- Change one thing at a time and retest.
Exercise
A callout works for you, but the first sales user who tries it gets an error about missing authentication. The External Credential uses a per user principal. Name two things to check and the action the user must take.
Show answer
Check that the user's permission sets include External Credential Principal Access for that per user principal, and that the Named Credential points to the right External Credential. Then the user must authenticate once to the external system from their own settings (External Credentials, or Authentication Settings for External Systems). It works for you because you already authenticated.
Exercise
The endpoint callout:Weather_API/forecast returns 404. The Named Credential URL is https://api.example.com/v1/forecast. What is the likely cause, and how do you fix it?
Show answer
The path is duplicated, so the final URL is https://api.example.com/v1/forecast/forecast. Remove /forecast from the Named Credential URL (leaving https://api.example.com/v1) or from the Apex endpoint, so the path appears in only one place.