[SalesForce] Error Handling in REST Webservice

I have exposed this Apex class as a webservice. So far so good, as I get the response when this Webservice is called from ARC or POstman.

@RestResource(urlMapping='/ProcessAccount/*') 

global with sharing class AccountManager {

    @HttpGet
    global static list<Account> getAccountById() {

       RestRequest req = RestContext.request;
       String recordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Supplier_Account').getRecordTypeId();
       String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
       system.debug('The account is: ' +accountId);


       list<Account> result =  [SELECT ID, Supplier_ID__c,Name, BillingStreet, BillingCity, BillingState, BillingPostalCode, 
                                    BillingCountry, Phone, 
                                    RecordTypeId, CreatedDate,LastModifiedDate, SystemModstamp 
                                    FROM Account 
                                    WHERE RecordTypeId = :recordTypeId AND Id = :accountId limit 1];

        system.debug('Check the list size ' + result.size());
        return result;

    }


}

My question is, how can I add error handling in this class. How can i make it good enough to confidentially deploy to production along with the test class. ?

Thank You

Best Answer

I don't believe that this code can throw any system exceptions at all. If no Accounts are found, or if the input is nonsensical, the class will simply return an empty list.

You need to add more code only if you want to provide a semantic response for the caller, such as "this request doesn't make sense", "no matching Account found", etc. In that case you would define your own error codes, check for the error state, and return some kind of composite response like

public class Response {
    List<Account> results;
    Integer errorCode;
}
Related Topic