How do developers structure exception handling in custom Apex REST services to return clean error payloads?
Answer
Basics: Apex REST exposes classes annotated @RestResource as endpoints. If an uncaught exception escapes, Salesforce returns HTTP 500 with a generic error array, which is unhelpful and leaks internals. Clients need predictable codes and messages.
How it works:
- Wrap each handler body in try/catch.
- Validate input first and return 400 for bad requests, 404 for missing records, 409 for conflicts, 500 for unexpected failures.
- Set
RestContext.response.statusCodeandresponseBody = Blob.valueOf(JSON.serialize(err)), plusContent-Type: application/json. - Log details internally and return only a safe message and a correlation ID to the caller.
- Use partial success DML (
Database.insert(records, false)) when a batch may partially succeed.
Advanced / deep dive: Use a custom exception hierarchy (BadRequestException, NotFoundException) mapped centrally, so handlers stay clean. Return 200/201/207-style multi-status bodies for bulk endpoints. Do not expose stack traces or SOQL text. Declare idempotency keys for POSTs. Remember that if you set statusCode and also return a value, the framework serializes the return value, so for errors set the body explicitly. Test with RestContext.request/response set manually. Enforce with sharing and WITH USER_MODE/WITH SECURITY_ENFORCED as appropriate since REST classes run in system mode by default regarding CRUD/FLS.
Code / config example:
@RestResource(urlMapping='/orders/*')
global with sharing {
{ Integer status; }
global {
RestContext.response;
res.addHeader(, );
{
Map<String,Object> body = (Map<String,Object>) JSON.deserializeUntyped(RestContext.request.requestBody.toString());
(!body.containsKey()) { (); e.status = ; e; }
(Account__c = (Id) body.get());
insert o;
res.statusCode = ;
res.responseBody = Blob.valueOf(JSON.serialize( <String,Object>{ => o.Id}));
} (ApiException e) {
res.statusCode = e.status; res.responseBody = Blob.valueOf(JSON.serialize( <String,String>{ => e.getMessage()}));
} (Exception e) {
res.statusCode = ; res.responseBody = Blob.valueOf(JSON.serialize( <String,String>{ => }));
}
}
}