Sub topic 9
Reading and handling error responses
This chapter assumes you can build a resource URL, send an authenticated request, and use POST, GET, and PATCH on an sObject. Here you learn what a failed request looks like and how to handle it in code.
The shape of an error
When a REST API call fails, Salesforce returns a 4xx or 5xx status code. The body is a JSON array of error objects. It is always an array, even when there is only one error.
[
{
"message": "Required fields are missing: [Name]",
"errorCode": "REQUIRED_FIELD_MISSING",
"fields": ["Name"]
}
]Each object has these keys:
messageis text for people. Wording can change, so don't match on it.errorCodeis a stable string for code. Branch on this value.fieldslists the fields involved. It is empty for errors that are not tied to a field.
Common status codes and error codes
| Status | Typical `errorCode` | Usual cause | What to do |
|---|---|---|---|
| 400 | `REQUIRED_FIELD_MISSING`, `MALFORMED_QUERY`, `INVALID_FIELD` | The request body or query is wrong | Fix the data. Do not retry unchanged. |
| 401 | `INVALID_SESSION_ID` | The access token is expired or revoked | Get a new token, then retry once. |
| 403 | `REQUEST_LIMIT_EXCEEDED`, `INSUFFICIENT_ACCESS` | A limit was hit, or the user lacks permission | Back off, or fix permissions. |
| 404 | `NOT_FOUND` | Wrong URL, or the record ID does not exist | Check the URL, version, and ID. |
| 5xx | varies | A problem on the Salesforce side | Retry later with a delay. |
A 400 means the problem is in your request. A 401 means the credentials need refreshing. Only some 5xx and limit errors are worth retrying.
The decision flow
The diagram shows how a client can react to each outcome.
Handling errors in Python
Raising a generic exception loses the details. This version parses the array and keeps the errorCode values so callers can branch on them.
import requests
class SalesforceError(Exception):
def __init__(self, status_code, errors):
self.status_code = status_code
self.errors = errors
codes = ", ".join(e.get("errorCode", "?") for e in errors)
messages = "; ".join(e.get("message", "") for e in errors)
super().__init__(f"{status_code} [{codes}] {messages}")
def has_code(self, code):
return any(e.get("errorCode") == code for e in self.errors)
def check(response):
if response.ok:
return response
try:
errors = response.json()
except ValueError:
errors = [{"errorCode": "NON_JSON_ERROR", "message": response.text}]
if not isinstance(errors, list):
errors = [errors]
raise SalesforceError(response.status_code, errors)
# Example: a create call with no Name
# instance_url, version, and headers are set up as in the earlier chapters
# response = requests.post(f"{instance_url}/services/data/{version}/sobjects/Account",
# headers=headers, json={"Industry": "Technology"}, timeout=30)
# try:
# check(response)
# except SalesforceError as err:
# if err.has_code("REQUIRED_FIELD_MISSING"):
# print("Add a Name and try again")
# else:
# raiseThe fallback for non-JSON bodies matters. A gateway or proxy in front of Salesforce can return an HTML error page, and calling .json() on it would raise a confusing second error.
Common mistakes
- Reading
response.json()["message"]as if the body were an object. It is a list, so use[0]["message"]or loop over it. - Retrying a 400 in a loop. The same bad input fails every time.
- Retrying a 401 forever. Refresh the token once. If the second call also returns 401, stop and report it.
- Logging only the status code. Always log the body, because the
errorCodeis in it. - Matching on
messagetext instead oferrorCode.
Exercise
Your script calls PATCH on an Account and gets a 401 with errorCode INVALIDSESSIONID. Should it retry the same request immediately? What should it do instead?
Show answer
No. The token is expired or revoked, so the same request fails again. The script should obtain a new access token, then retry the request once. If the retry also returns 401, it should stop and report the error instead of looping.
Exercise
A create call returns this body: [{"message":"Required fields are missing: [Name]","errorCode":"REQUIREDFIELDMISSING","fields":["Name"]}]. Which status code do you expect, and which key should your code branch on?
Show answer
A 400 status. Branch on errorCode (REQUIREDFIELDMISSING), not on message, because the message text is meant for people and can change.