global class AccountError {
    global static Account doPost(){
        string jsonResponse='';
        RestRequest request = RestContext.request;
        RestResponse response = RestContext.response;
        String requestBody = System.RestContext.request.requestBody.toString();
        AccWrapperError acc = (AccWrapperError)JSON.deserialize(requestBody,AccWrapperError.class);

            if(string.isBlank(acc.Name) || string.isBlank(acc.phone))
                throw new accountCodeException('Fields should not be Empty');
            Account accRecord = new Account();
            accRecord.Name = acc.Name;
            accRecord.Phone = acc.Phone;
            accRecord.Rating = acc.Rating;
            insert accRecord;
            return accRecord;
        catch (accountCodeException e) {
            accountCodeException aa;
            throw new accountCodeException('New error '{errorCode:201,errorMessage:+e.getMessage()});

    public class accountCodeException extends Exception {
  • 3
    Welcome to Salesforce Stack Exchange (SFSE)! Thank you for the code, but you need to please edit your question to also add exactly (e.g., exact error text, details of unexpected behavior) how it is not working. (From What topics can I ask about here?: 'Your question should include...A specific, detailed description of the issue ("it doesn’t work" is not enough to allow the community to help).')
    – Moonpie
    Jul 26, 2022 at 12:32

1 Answer 1


you can try using a new apex class, with two properties: code and message:

public class CustomExceptionResponse {
    private String code;
    private String message;
    public CustomExceptionResponse(String code, String message) {
        this.code = code;
        this.message = message;

and then when you throw your custom exception, serialize the object, something like this:

catch (Exception e) {
   String error = JSON.serialize(new CustomExceptionResponse('201', 'Your Custom Message Here plus: ' + e.getMessage()));
   throw new accountCodeException(error);

Hope this helps!

Not the answer you're looking for? Browse other questions tagged .