# How do developers structure exception handling in custom Apex REST services to return clean error payloads?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, Exception Handling, Apex REST Errors

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
1. Wrap each handler body in try/catch.
2. Validate input first and return 400 for bad requests, 404 for missing records, 409 for conflicts, 500 for unexpected failures.
3. Set `RestContext.response.statusCode` and `responseBody = Blob.valueOf(JSON.serialize(err))`, plus `Content-Type: application/json`.
4. Log details internally and return only a safe message and a correlation ID to the caller.
5. 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:**
```apex
@RestResource(urlMapping='/orders/*')
global with sharing class OrderApi {
    public class ApiException extends Exception { public Integer status; }
    @HttpPost
    global static void createOrder() {
        RestResponse res = RestContext.response;
        res.addHeader('Content-Type', 'application/json');
        try {
            Map<String,Object> body = (Map<String,Object>) JSON.deserializeUntyped(RestContext.request.requestBody.toString());
            if (!body.containsKey('accountId')) { ApiException e = new ApiException('accountId required'); e.status = 400; throw e; }
            Order__c o = new Order__c(Account__c = (Id) body.get('accountId'));
            insert o;
            res.statusCode = 201;
            res.responseBody = Blob.valueOf(JSON.serialize(new Map<String,Object>{'id' => o.Id}));
        } catch (ApiException e) {
            res.statusCode = e.status; res.responseBody = Blob.valueOf(JSON.serialize(new Map<String,String>{'error' => e.getMessage()}));
        } catch (Exception e) {
            res.statusCode = 500; res.responseBody = Blob.valueOf(JSON.serialize(new Map<String,String>{'error' => 'Internal error'}));
        }
    }
}
```

**Hidden gotchas & must-remember points:**
- An uncaught exception yields a generic 500 with an error array.
- Apex REST ignores object/field security unless you enforce it.
- Type-cast failures from `deserializeUntyped` are runtime exceptions; catch them.
- The `Content-Type` header must be set for clients to parse JSON.
- Response size limits follow heap limits (6 MB sync).
- Global classes and methods are required for managed package exposure.

**Best practice:** Central error mapping with stable error codes, safe messages and internal logging.

---
Source: ForceChallenges · last updated 2026-11-02
