Sub topic 7
Returning status codes and handling errors
A client of your service reads the HTTP status code before it reads anything else. This chapter covers how to set that code from Apex, which codes to use, what the platform does when your code fails, and how to turn exceptions into consistent JSON error bodies.
This chapter assumes you can write a @RestResource class with @HttpGet and @HttpPost methods, read RestContext.request, and serialize objects with JSON.serialize. It also assumes you know the standard HTTP status code families.
What the platform does by default
If you set nothing, Apex REST returns 200 OK when your method finishes. If you throw an exception that nothing catches, the platform returns 500 and puts the exception message in the response body. That message can include class names and internal details, and clients can't branch on it reliably.
The platform also answers some requests before your code runs:
| Situation | Typical status |
|---|---|
| No `@RestResource` class matches the URL | 404 |
| The URL matches but no method has the right HTTP annotation | 405 |
| The access token is missing, invalid, or expired | 401 |
| The user's profile or permission set lacks access to the Apex class | 403 |
| The JSON body can't be bound to your method parameters | 400 |
| An exception escapes your method | 500 |
You can't customize these. Your job is to handle everything that happens inside your methods.
Setting the status code
RestContext.response is a RestResponse. Assign an integer to statusCode and the platform sends it.
RestResponse res = RestContext.response;
res.statusCode = 404;There are two styles for the body, and you should pick one per method.
- Return a value from the method. The platform serializes it to JSON. This works well for the success path, but it makes error bodies awkward because the error must be the same type as the success value.
- Declare the method
voidand writeres.responseBodyyourself. This lets you return a different shape for errors. The examples below use this style.
A void method with no body assignment sends an empty body, which is correct for 204 No Content.
Choosing the right code
Pick a code by asking who must change something to make the request work.
| Code | Use it when |
|---|---|
| 200 | A GET, PUT, or PATCH succeeded and you return a body |
| 201 | A POST created a record. Include the new Id |
| 204 | The operation succeeded and there is nothing to return, such as DELETE |
| 400 | The request is malformed or fails validation. The client must fix it |
| 403 | The caller is authenticated but not allowed to see or change this data |
| 404 | The requested record doesn't exist, or the caller can't see it |
| 409 | The request conflicts with current state, such as a duplicate |
| 500 | A bug or unexpected failure on your side |
Two choices come up often:
- A record hidden by sharing and a record that doesn't exist both look like zero rows from a user-mode query. Returning
404for both is safe because it doesn't reveal that the record exists. - Don't return
200with"success": falsein the body. Clients and monitoring tools look at the status code first, so a failure sent as200goes unnoticed.
A consistent error body
Clients can write one error handler if every error has the same shape. Put the shape and the sending logic in one helper class.
public with sharing class RestErrors {
public class ErrorBody {
public String errorCode;
public String message;
}
public static void send(RestResponse res, Integer status, String code, String message) {
ErrorBody body = new ErrorBody();
body.errorCode = code;
body.message = message;
res.statusCode = status;
res.addHeader('Content-Type', 'application/json');
res.responseBody = Blob.valueOf(JSON.serialize(body));
}
public static void sendJson(RestResponse res, Integer status, Object payload) {
res.statusCode = status;
res.addHeader('Content-Type', 'application/json');
res.responseBody = Blob.valueOf(JSON.serialize(payload));
}
}errorCode is a short, stable string that clients can compare against. message is for humans and may change.
Validating input first
Check the input before you query or write. The most common bug in a path-based endpoint is passing a bad string to SOQL. Binding an invalid Id string to an Id field throws a QueryException, which would turn a client mistake into a server error. Parse the Id yourself and return 400.
@RestResource(urlMapping='/v2/Accounts/*')
global with sharing class AccountErrorService {
@HttpGet
global static void getAccount() {
RestResponse res = RestContext.response;
String idText = RestContext.request.requestURI.substringAfterLast('/');
if (String.isBlank(idText)) {
RestErrors.send(res, 400, 'MISSING_ID', 'Append an Account Id to the URL.');
return;
}
Id accountId;
try {
accountId = Id.valueOf(idText);
} catch (StringException e) {
RestErrors.send(res, 400, 'INVALID_ID', 'The value "' + idText + '" is not a valid Id.');
return;
}
try {
List<Account> rows = [
SELECT Id, Name, Industry
FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];
if (rows.isEmpty()) {
RestErrors.send(res, 404, 'NOT_FOUND', 'No Account found for that Id.');
return;
}
RestErrors.sendJson(res, 200, rows[0]);
} catch (QueryException e) {
RestErrors.send(res, 403, 'INSUFFICIENT_ACCESS', 'You do not have access to read Accounts.');
}
}
}Notice the order. Blank check, then format check, then the query. Each failure returns early, so the success path stays at the bottom with no nesting. The QueryException catch handles a user who lacks read access to the object or a queried field, because WITH USER_MODE enforces it by throwing.
Don't echo large or sensitive input back into error messages. The invalid Id above is short and came from the caller, so it is acceptable.
Handling DML failures
DML can fail for validation rules, required fields, triggers, duplicate rules, and permissions. You have two ways to handle this.
With plain insert or update, any failure throws a DmlException. Catch it and map it to a status.
@HttpPost
global static void createAccount(String name, String industry) {
RestResponse res = RestContext.response;
if (String.isBlank(name)) {
RestErrors.send(res, 400, 'MISSING_NAME', 'The name field is required.');
return;
}
try {
Account acc = new Account(Name = name, Industry = industry);
insert as user acc;
RestErrors.sendJson(res, 201, new Map<String, Object>{ 'id' => acc.Id });
} catch (DmlException e) {
RestErrors.send(res, 400, 'DML_ERROR', e.getDmlMessage(0));
} catch (Exception e) {
System.debug(LoggingLevel.ERROR, e.getMessage() + '\n' + e.getStackTraceString());
RestErrors.send(res, 500, 'SERVER_ERROR', 'An unexpected error occurred.');
}
}getDmlMessage(0) returns only the first error's text, without the wrapper that getMessage() adds. Add this method to AccountErrorService.
The last catch block does two jobs. It logs the real cause for you, and it gives the client a generic message. This keeps stack traces and internal details out of the response while still returning a clean JSON body instead of the platform's default 500 output.
With Database.insert(records, false), nothing is thrown. You get a list of SaveResult objects and inspect each one. Use this for endpoints that accept several records, so one bad row doesn't block the rest. Chapter 13 covers bulk design.
The decision flow
Edge cases
- Set the status before you return. Once the method returns, you can't change it. Set it in the same block that writes the body.
- Don't throw a custom exception to signal a client error. An uncaught exception always becomes a
500. Catch it inside the method and call your helper. - Rollback is not automatic when you catch. If you do several DML statements and the second one fails, the first one stays committed unless you use a savepoint. Use
Database.setSavepoint()andDatabase.rollback(sp)in the catch block when the operations must succeed together. - Unhandled limit exceptions can't be caught. A
System.LimitExceptionends the transaction and is not catchable, so the client gets the platform's500response. Validate batch sizes up front to avoid this. - A
204must have no body. Don't write toresponseBodyfor it.
Testing the error paths
Tests for error paths need no HTTP call. Build a request, run the handler, and read the status from the response object.
@IsTest
private class AccountErrorServiceTest {
private static RestResponse run(String uri) {
RestRequest req = new RestRequest();
req.requestURI = uri;
req.httpMethod = 'GET';
RestResponse res = new RestResponse();
RestContext.request = req;
RestContext.response = res;
AccountErrorService.getAccount();
return res;
}
@IsTest
static void badIdReturns400() {
RestResponse res = run('/services/apexrest/v2/Accounts/not-an-id');
Assert.areEqual(400, res.statusCode);
Assert.isTrue(res.responseBody.toString().contains('INVALID_ID'));
}
@IsTest
static void unknownIdReturns404() {
RestResponse res = run('/services/apexrest/v2/Accounts/001000000000000AAA');
Assert.areEqual(404, res.statusCode);
}
}The Id 001000000000000AAA is well formed, so it passes Id.valueOf and reaches the query, where no row matches. Always test both the 400 and 404 branches, because they fail for different reasons.
Exercise
A client sends POST with a valid body, but a validation rule on Account rejects the insert. Your handler has catch (DmlException e) that sets status 400. Where should the error text come from, and why is returning 200 with a success flag in the body a poor alternative?
Show answer
Take the text from e.getDmlMessage(0), which gives the validation rule's message for the first failed row without the exception wrapper. Returning 200 with a flag is poor because clients, proxies, and monitoring tools read the status code first and would treat the failed request as a success. A 400 tells them the request itself must change.
Exercise
Why does the GET handler call Id.valueOf in a try block instead of binding the URL segment straight into the SOQL query?
Show answer
A string that isn't a valid Id causes a QueryException when bound to an Id field. That would look like a permission failure or a server error, although the client simply sent bad input. Parsing first lets the handler return 400 INVALID_ID, which describes the real problem.