Sub topic 7
Returning status codes and handling errors
This chapter assumes you can write a basic @RestResource class, read RestContext.request, and use try/catch with DML. It covers how to tell a client what happened: which status code to set, what body to send, and how to keep unhandled exceptions from leaking.
Why status codes matter
A client decides what to do next from the HTTP status code before it reads the body. If your service returns 200 for every outcome and puts the real result in the body, every client has to learn your private convention. Use the standard codes instead.
| Code | Use it when |
|---|---|
| 200 | A GET or PATCH succeeded and you return a body |
| 201 | A POST created a record |
| 204 | A DELETE succeeded and there is nothing to return |
| 400 | The input is invalid or DML failed on bad data |
| 404 | The requested record does not exist |
| 405 | The method is not supported for this resource |
| 500 | An unexpected server error |
Setting the status code
Set the code on RestContext.response before you return. If you do not set one, Salesforce sends 200 on a normal return.
RestResponse res = RestContext.response;
res.statusCode = 404;The earlier @HttpGet example does this when the query returns no rows. Note that it returns null. A client then receives the 404 with an empty body, which is hard to debug.
Returning a consistent error body
Define one error shape and use it everywhere. Clients can then parse failures the same way for every endpoint.
global class ApiError {
global String code;
global String message;
global ApiError(String code, String message) {
this.code = code;
this.message = message;
}
}Handler methods can return different types, so a method that returns Account on success cannot return ApiError on failure. There are two common ways to handle this:
- Return a wrapper class with fields for both the data and the error, as
CreateResultdoes in the POST example. - Return
void, and write the JSON yourself withres.responseBody = Blob.valueOf(JSON.serialize(body))plus aContent-Typeheader.
The second approach gives you full control, so the example below uses it.
@RestResource(urlMapping='/v1/Contacts/*')
global with sharing class ContactRestService {
@HttpDelete
global static void deleteContact() {
RestResponse res = RestContext.response;
res.addHeader('Content-Type', 'application/json');
String contactId = RestContext.request.requestURI.substringAfterLast('/');
if (String.isBlank(contactId) || !(contactId instanceof Id)) {
writeError(res, 400, 'INVALID_ID', 'A valid Contact Id is required.');
return;
}
try {
List<Contact> rows = [
SELECT Id FROM Contact WHERE Id = :contactId WITH USER_MODE LIMIT 1
];
if (rows.isEmpty()) {
writeError(res, 404, 'NOT_FOUND', 'No Contact with that Id.');
return;
}
delete as user rows;
res.statusCode = 204;
} catch (DmlException e) {
writeError(res, 400, 'DML_ERROR', e.getDmlMessage(0));
} catch (Exception e) {
writeError(res, 500, 'SERVER_ERROR', 'Unexpected error.');
}
}
private static void writeError(RestResponse res, Integer status, String code, String message) {
res.statusCode = status;
res.responseBody = Blob.valueOf(JSON.serialize(new ApiError(code, message)));
}
}How errors flow
Common errors
- Letting exceptions escape. An uncaught exception makes Salesforce return 500 with an Apex stack-trace style message. Catch it, log it with
System.debugor your own logging, and return a generic message. - Catching
Exceptionfirst. Order catch blocks from most to least specific.DmlExceptionmust come beforeException, or the code will not compile. - Returning 200 with an error body. Clients that check only the status code treat the call as a success.
- Using
e.getMessage()for DML errors. It can include internal wording.getDmlMessage(0)returns the message for the first failed row. - Setting the body and status but forgetting the content type. Clients may not parse the body as JSON.
Exercise
A client calls your @HttpPost method with a missing required field, and the insert throws a DmlException. Which status code should you set, and why not 500?
Show answer
Set 400. The problem is bad input from the client, not a fault in your service. A 500 tells the client the server failed and may lead it to retry the same bad request.
Exercise
Your @HttpGet method returns an Account, and the record is not found. You set statusCode to 404 and return null. What is the drawback, and how can you fix it?
Show answer
The client gets a 404 with an empty body and no explanation. Change the method to return void, build an ApiError, serialize it into res.responseBody, and set the Content-Type header to application/json.