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
Rajesh Singh 88Rajesh Singh 88 

Send failed record Ids as response along with Failed status message and error code in a REST based post method

I am new to integration so need some help on my work.

I have a requirement to get the request from an external system and update the data in salesforce. I am able to successfully update the data and send the success response but I am unable to send the failed record Ids and the failed status message.

Below is the code which I have written:

@RestResource(urlMapping='/AccSlaExpireDate/*')
global class AccountSLAExpirationDateUpdate {
    @HttpPost 
    global static void updateAccSLAExpDate(){
        RestRequest accSlaDateRequest = RestContext.request;
        String jsonResponse = '';
        RestResponse res = RestContext.response;
        
        String requestBody = accSlaDateRequest.requestBody.toString();
        system.debug('requestBodyVal'+requestBody);
        List<accountSLAExpDate> accDateReceived = (List<accountSLAExpDate>) JSON.deserialize(requestBody, List<accountSLAExpDate>.class);
        System.debug('listSizeVal'+accDateReceived.size());
        List<Account> accListToUpdate = new List<Account>();
        
        for(accountSLAExpDate accDate : accDateReceived){
            Account acc = new Account();
            acc.Id = Id.valueOf(accDate.ACCOUNT_SOURCE_REF);
            If(accDate.SLAEXPDATE != ''){
                acc.SLAExpirationDate__c = Date.valueOf(accDate.SLAEXPDATE);
            }else{
                acc.SLAExpirationDate__c = NULL;
            } 
            accListToUpdate.add(acc);
        }
        
        Database.SaveResult[] srList = database.update(accListToUpdate,false);
        
        for (Database.SaveResult sr : srList){
            if (sr.isSuccess()){
                jsonResponse = '{"response": {"status": "Successfully updated"}}';
                res.responseBody = blob.valueOf(jsonResponse);
                return;
            }else {
                // Operation failed, so get all errors                
                for(Database.Error err : sr.getErrors()) {
                    System.debug('The following error has occurred.'+sr.getId());                    
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('Account fields that affected this error: ' + err.getFields());
                }
            }
        }
    }
    global class accountSLAExpDate{
        public String ACCOUNT_SOURCE_REF;  //Account Id
        public String SLAEXPDATE;  //yyyy-mm-dd format
    }
}

I have tested with the below REST API service URI :

/services/apexrest/AccSlaExpireDate/

Payload: 
[
    {
      "ACCOUNT_SOURCE_REF": "0012x0000059fPD",
      "SLAEXPDATE": "2021-02-08"
    }
]

Can someone please help on how to send the failed record Ids and failed records status message as response back to the external system.
Best Answer chosen by Rajesh Singh 88
mukesh guptamukesh gupta
Hi Rajsh,

Please follow below code:-

 
@RestResource(urlMapping='/AccSlaExpireDate/*')
global class AccountSLAExpirationDateUpdate {
    @HttpPost 
    global static List<ResponseWrapper> updateAccSLAExpDate(){
        RestRequest accSlaDateRequest = RestContext.request;
        String jsonResponse = '';
        RestResponse res = RestContext.response;
        
        String requestBody = accSlaDateRequest.requestBody.toString();
        system.debug('requestBodyVal'+requestBody);
        List<accountSLAExpDate> accDateReceived = (List<accountSLAExpDate>) JSON.deserialize(requestBody, List<accountSLAExpDate>.class);
        System.debug('listSizeVal'+accDateReceived.size());
        List<Account> accListToUpdate = new List<Account>();
		
		//////////////// wraper list ///////////////////////
        List<ResponseWrapper> wrperlist = new List<ResponseWrapper>();
		/////////////////////////////////////////////////
        for(accountSLAExpDate accDate : accDateReceived){
            Account acc = new Account();
            acc.Id = Id.valueOf(accDate.ACCOUNT_SOURCE_REF);
            If(accDate.SLAEXPDATE != ''){
                acc.SLAExpirationDate__c = Date.valueOf(accDate.SLAEXPDATE);
            }else{
                acc.SLAExpirationDate__c = NULL;
            } 
            accListToUpdate.add(acc);
        }
        
        Database.SaveResult[] srList = database.update(accListToUpdate,false);
        
        for (Database.SaveResult sr : srList){
            if (sr.isSuccess()){
				
			    
                jsonResponse = '{"response": {"status": "Successfully updated"}}';
                res.responseBody = blob.valueOf(jsonResponse);
				wrperlist.add(new ResponseWrapper(res.responseBody.Id,status)); /// you need to parse and check it
				
                //return;
            }else {
			   res.responseBody = Blob.valueOf(err.getMessage());
			   wrperlist.add(new ResponseWrapper(res.responseBody.Id,res.statusCode)); /// you need to parse and check it
               //res.statusCode = 500;
			   //return;
                // Operation failed, so get all errors                
                /*for(Database.Error err : sr.getErrors()) {
                    System.debug('The following error has occurred.'+sr.getId());                    
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('Account fields that affected this error: ' + err.getFields());
                }*/
            }
        }
		
		return wrperlist;
    }
    global class accountSLAExpDate{
        public String ACCOUNT_SOURCE_REF;  //Account Id
        public String SLAEXPDATE;  //yyyy-mm-dd format
    }
}


///////////////////////////////////////////  wrapper class ///////////////////////////////////

public class ResponseWrapper{
    public String Id ;
    public string errorStatus;
    public integer errorCode;
       public ResponseWrapper(String Id, String statusCode){
        this.Id  = Id;
        this.errorStatus = statusCode;
    }

}



if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh 

All Answers

mukesh guptamukesh gupta
Hi Rajsh,

Please follow below code:-

 
@RestResource(urlMapping='/AccSlaExpireDate/*')
global class AccountSLAExpirationDateUpdate {
    @HttpPost 
    global static List<ResponseWrapper> updateAccSLAExpDate(){
        RestRequest accSlaDateRequest = RestContext.request;
        String jsonResponse = '';
        RestResponse res = RestContext.response;
        
        String requestBody = accSlaDateRequest.requestBody.toString();
        system.debug('requestBodyVal'+requestBody);
        List<accountSLAExpDate> accDateReceived = (List<accountSLAExpDate>) JSON.deserialize(requestBody, List<accountSLAExpDate>.class);
        System.debug('listSizeVal'+accDateReceived.size());
        List<Account> accListToUpdate = new List<Account>();
		
		//////////////// wraper list ///////////////////////
        List<ResponseWrapper> wrperlist = new List<ResponseWrapper>();
		/////////////////////////////////////////////////
        for(accountSLAExpDate accDate : accDateReceived){
            Account acc = new Account();
            acc.Id = Id.valueOf(accDate.ACCOUNT_SOURCE_REF);
            If(accDate.SLAEXPDATE != ''){
                acc.SLAExpirationDate__c = Date.valueOf(accDate.SLAEXPDATE);
            }else{
                acc.SLAExpirationDate__c = NULL;
            } 
            accListToUpdate.add(acc);
        }
        
        Database.SaveResult[] srList = database.update(accListToUpdate,false);
        
        for (Database.SaveResult sr : srList){
            if (sr.isSuccess()){
				
			    
                jsonResponse = '{"response": {"status": "Successfully updated"}}';
                res.responseBody = blob.valueOf(jsonResponse);
				wrperlist.add(new ResponseWrapper(res.responseBody.Id,status)); /// you need to parse and check it
				
                //return;
            }else {
			   res.responseBody = Blob.valueOf(err.getMessage());
			   wrperlist.add(new ResponseWrapper(res.responseBody.Id,res.statusCode)); /// you need to parse and check it
               //res.statusCode = 500;
			   //return;
                // Operation failed, so get all errors                
                /*for(Database.Error err : sr.getErrors()) {
                    System.debug('The following error has occurred.'+sr.getId());                    
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('Account fields that affected this error: ' + err.getFields());
                }*/
            }
        }
		
		return wrperlist;
    }
    global class accountSLAExpDate{
        public String ACCOUNT_SOURCE_REF;  //Account Id
        public String SLAEXPDATE;  //yyyy-mm-dd format
    }
}


///////////////////////////////////////////  wrapper class ///////////////////////////////////

public class ResponseWrapper{
    public String Id ;
    public string errorStatus;
    public integer errorCode;
       public ResponseWrapper(String Id, String statusCode){
        this.Id  = Id;
        this.errorStatus = statusCode;
    }

}



if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh 
This was selected as the best answer
Rajesh Singh 88Rajesh Singh 88
Hi Mukesh,

Thanks for the reply!

I am getting couple of below errors while saving the class
  • Variable does not exist: Id
  • Variable does not exist: status
These errors are coming for the below lines:

wrperlist.add(new ResponseWrapper(res.responseBody.Id,status));

wrperlist.add(new ResponseWrapper(res.responseBody.Id,res.statusCode));

Can you please help me to resolve this.

Thanks,
Rajesh