function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SamuelDeRyckeSamuelDeRycke 

REST Webservice exception handling ?

I'm wondering, what the best practise is on dealing with exceptions when making a REST service in apex.

 

@HttpGet    	
    global static List<Account> getMyAccounts(){
    	//Purpose: get a list of all accounts(with details) a user is "related to" || customer portal user context    
    	//--> account the user's contact is under, and any possible sub accounts
    	try{
		   string userId =integer.valueof( RestContext.request.params.get('userid'));
		   
		   User user = [select id, name, accountId from user where id =:userId];
		   
		   List<Account> result = new List<Account>();
		   
		   //portal users always have accountId=accountid from contact which they were made out of
		   Account masteraccount = [select id from account where id in (select accountid from user where id=:user.accountID)]; //user.accountID only set on customer portal users
		   
		   //query for accounts having the above account as parentaccount

                  //something goes wrong !
		   
    	}catch(Exception x){
    		
                // Need to return a list of accounts, how show an errormessage or deal with this in a robust manner ?
    		return null;
    	}
    }

 As you can see in the comments in the posted code, I'm wondering what is best practise, on what should be returned. Just returning an empty resultset or null would not reveal any error and misguide the consuming code. What is a good way to expose and error easily picked up by the consuming code, without revealing too much internal detail of the exception ?

 

Are there other aspects (security/access wise) I should really pay attention too and implement in every REST service ? And/or is there a way to deal with such things in a generic way across services i'll be making ?  I find a lot of basic examples out there, but I've not found anything advanced covering a full real implementation, or am I just worrying too much .. 

Anup JadhavAnup Jadhav

Hello Sdry,

 

This is a very interesting question, and I'm glad you brought it up. I have come across this question when I was building REST webservices using Java (specifically using Spring MVC), and I found this gem of an article that describes what an ideal response should look like.  This article also points you to another great blog post by the folks at Apigee.

 

I'd recommend reading both articles. The gist seems to be that you should return the appropriate http status code along with human readable error message wrapped in a json.

 

This is obviously not the final say on the topic but a recommended approach. I'd interested to hear from others how they've handled this situation.

 

Regards,

Anup