Sub topic 9
Reading and handling error responses
This chapter assumes you can already create, read, and update records with POST, GET, and PATCH. It also assumes you know how bearer tokens work and can read JSON in curl or Python. Here you will learn how Salesforce reports failures, how to read the status code and error body together, and how to write a client that reacts to each failure correctly.
The shape of an error response
When a request fails, Salesforce returns a 4xx or 5xx status code and a JSON array of error objects. The body is an array even when there is only one error. Each object has these keys:
messageis text for humans. It can change between releases, so do not match on it.errorCodeis a stable string for programs. Branch on this value.fieldsis a list of field API names involved in the error. It is empty for errors that are not tied to a field.
A create request with no Name produces this body with a 400 status:
[
{
"message": "Required fields are missing: [Name]",
"errorCode": "REQUIRED_FIELD_MISSING",
"fields": ["Name"]
}
]A successful create returns "success": true and an empty errors array. A failed create does not return that shape. If the HTTP status is not 2xx, parse the body as an error array.
The array can hold several objects. Several validation failures on one record can arrive together, so loop over the whole array instead of reading only the first element.
The OAuth token endpoint is separate from the REST API. It reports failures as a single object, such as {"error": "invalid_grant", "error_description": "expired access/refresh token"}. Do not use your REST error parser on that endpoint.
Status code first, errorCode second
Use the status code to choose a strategy. Use the errorCode to find the specific cause.
| Status | Typical `errorCode` | Meaning | What to do |
|---|---|---|---|
| 400 | `REQUIRED_FIELD_MISSING`, `INVALID_FIELD`, `STRING_TOO_LONG`, `MALFORMED_ID`, `JSON_PARSER_ERROR`, `FIELD_CUSTOM_VALIDATION_EXCEPTION` | The request is invalid | Fix the data or request. Do not retry unchanged. |
| 401 | `INVALID_SESSION_ID` | The token is expired or invalid | Get a new token, then retry once. |
| 403 | `INSUFFICIENT_ACCESS`, `REQUEST_LIMIT_EXCEEDED` | The user lacks permission, or an API limit was hit | Check permissions, or stop and wait. |
| 404 | `NOT_FOUND` | The record or resource does not exist, or the user cannot see it | Check the ID, API version, and URL path. |
| 405 | `METHOD_NOT_ALLOWED` | The HTTP method is not valid for this URL | Use the right method. |
| 415 | `UNSUPPORTED_MEDIA_TYPE` | The `Content-Type` header is missing or wrong | Send `application/json`. |
| 500, 503 | `SERVER_UNAVAILABLE` and similar | A server-side problem | Retry with backoff. |
The first digit of the status gives you the policy:
- 4xx means your request is wrong. Retrying the same request will fail again.
- 5xx means the server has a problem. A retry might succeed.
- 401 is the one 4xx you can often fix automatically, because the same request works with a fresh token.
Common failures in detail
Expired session (401)
Access tokens expire. A request with an old token returns this body:
[
{
"message": "Session expired or invalid",
"errorCode": "INVALID_SESSION_ID"
}
]The same error appears if the token is malformed, was revoked, or belongs to a different org than the instance URL. If a freshly obtained token still returns 401, check that the instance URL matches the org that issued the token.
Missing or invalid fields (400)
A REQUIRED_FIELD_MISSING error lists the missing fields in fields. An INVALID_FIELD error means a field name does not exist on the object or is not visible to the user. Field names are case-insensitive but must match the API name, and custom fields end in __c. A STRING_TOO_LONG error means a value exceeds the field's length. A FIELD_CUSTOM_VALIDATION_EXCEPTION error means a validation rule in the org rejected the record. In that case message holds the rule's configured text.
Not found (404) and bad IDs (400)
A 404 NOT_FOUND usually means the record was deleted, the ID belongs to a different object type or org, or the user has no access. An ID that is not a valid Salesforce ID at all, such as abc, is reported as a 400 MALFORMED_ID. Also check the URL path and API version when you see 404, because a typo in /sobjects/Acount also produces a not-found error.
Wrong body or headers (400, 415)
A body that is not valid JSON gives JSON_PARSER_ERROR. A missing Content-Type: application/json header on a POST or PATCH can give a 415. When you use requests with the json= argument, the header is set for you.
Limits (403)
REQUEST_LIMIT_EXCEEDED means the org has used its API allowance. Retrying immediately makes no difference. The Sforce-Limit-Info response header on successful calls shows usage in the form api-usage=25/15000, so you can watch it before you hit the limit.
A client that handles errors
This script wraps the request logic in one function. It raises a typed exception that carries the status and the parsed error list. It refreshes the token once on 401 and retries 5xx responses with exponential backoff. The refresh_token function is a stub. Replace it with your own OAuth flow.
import os
import time
import requests
class SalesforceError(Exception):
def __init__(self, status, errors):
self.status = status
self.errors = errors # list of {message, errorCode, fields}
codes = ", ".join(e.get("errorCode", "?") for e in errors)
super().__init__(f"{status}: {codes}")
def has_code(self, code):
return any(e.get("errorCode") == code for e in self.errors)
def parse_errors(response):
try:
body = response.json()
except ValueError:
return [{"message": response.text, "errorCode": "NON_JSON_RESPONSE"}]
if isinstance(body, list):
return body
return [body] # e.g. an OAuth-style object
def refresh_token():
# Replace with a real OAuth refresh or re-authentication call.
return os.environ["SF_ACCESS_TOKEN"]
def sf_request(method, path, token, retries=3, **kwargs):
base = (
f"{os.environ['SF_INSTANCE_URL']}/services/data/"
f"{os.environ.get('SF_API_VERSION', 'v60.0')}"
)
refreshed = False
for attempt in range(retries + 1):
headers = {"Authorization": f"Bearer {token}"}
response = requests.request(
method, f"{base}{path}", headers=headers, timeout=30, **kwargs
)
if response.ok:
return response
if response.status_code == 401 and not refreshed:
token = refresh_token()
refreshed = True
continue
if response.status_code >= 500 and attempt < retries:
time.sleep(2 ** attempt)
continue
raise SalesforceError(response.status_code, parse_errors(response))
raise RuntimeError("unreachable")
if __name__ == "__main__":
token = os.environ["SF_ACCESS_TOKEN"]
try:
sf_request("POST", "/sobjects/Account", token, json={"Industry": "Technology"})
except SalesforceError as err:
if err.has_code("REQUIRED_FIELD_MISSING"):
for e in err.errors:
print("Missing:", e.get("fields"), "-", e["message"])
else:
raiseRunning this against an org prints the missing Name field, because the request omits it. Note that the 401 branch retries only once. A second 401 falls through to the raise, which prevents an infinite refresh loop when the problem is not an expired token.
Gotchas
- Do not retry POST blindly. If a POST times out, the record may have been created. Retrying can create a duplicate. Query for the record first, or use an upsert by external ID, which is safe to repeat.
- Parse the body even for 204. A successful PATCH has no body, so calling
response.json()on it raises an exception. Check the status before parsing. - Log the full body. The
messageoften names the exact field or rule. A message that says only "400" is useless for debugging. - Do not log tokens. Log the status,
errorCode, and URL, but never theAuthorizationheader. - Match on
errorCode, notmessage. Message text can be edited by admins, as with validation rules, or reworded between releases.
Exercise
Your script receives a 400 response whose body is [{"message": "No such column 'Industri' on sobject of type Account", "errorCode": "INVALID_FIELD", "fields": ["Industri"]}]. Should the script refresh the token and retry? What should it do instead?
Show answer
No. A 400 means the request itself is wrong, and a new token cannot change that. The INVALID_FIELD code and the fields list show that "Industri" is a misspelling of the API name Industry. Correct the field name in the request. Retrying the unchanged request will fail the same way.
Exercise
A PATCH call returns 204 and your code crashes with a JSON decoding error. What went wrong, and how do you fix it?
Show answer
A successful PATCH returns 204 No Content with an empty body, so response.json() has nothing to parse. Check response.ok or the status code first, and parse JSON only for responses that carry a body, such as a 201 from a create or any error response.