-3

I am working on a rest API using http post to get the params and create a record. After creating the record I need to send a response with the details of created record along with a status code and message in the response body. I am facing issues while implementing the code. below is my code:

@RestResource(urlMapping='/events/*')
global class createEvents {

    @HttpPost
    global static void createEvent(String subject, Datetime startDateTime, Datetime endDateTime, String psaRequestedBy, String recurs,Datetime recStartDateTime, Date recEndDate, Integer recurrenceDayOfWeekMask){

        RestRequest req= RestContext.request;
       RestResponse res = RestContext.response;

        String accountId= req.requestURI.substring(req.requestURI.lastindexOf('/')+1);

        List<Event> events = [select   ShowAs, Disable_Alarm__c, WhatId, Subject, ActivityDate, StartDateTime, EndDateTime, PSA_Requested_by__c, OwnerId, IsRecurrence, RecurrenceStartDateTime, RecurrenceEndDateOnly, RecurrenceType, RecurrenceDayOfWeekMask, RecurrenceInterval from Event
                              where WhatId= :accountId  limit 10];
        system.debug('events list***'+events);

        Event e;

        try{
            if(events.size() ==0){
               e = new Event();
               e.ShowAs = 'Busy';
               e.Disable_Alarm__c = true;
               e.WhatId = accountId;
               e.Subject = subject;
               e.StartDateTime = startDateTime;
               e.EndDateTime = endDateTime;
               e.PSA_Requested_by__c = psaRequestedBy;
               e.OwnerId = UserInfo.getUserId();

                insert e;
              }

              else if(events.size() >0){
                 for(Event eve : events){
             if((startDateTime <= eve.StartDateTime && endDateTime >=  eve.StartDateTime && endDateTime <= eve.EndDateTime) || 
                 (startDateTime <= eve.StartDateTime && endDateTime >= eve.StartDateTime && endDateTime >= eve.EndDateTime) ||
                 (startDateTime >=  eve.StartDateTime && startDateTime <= eve.EndDateTime)){

               // return 'already PSA exist';    
              // return '{\'status\':\'failure\',\'status_msg\':\'already PSA exist\'}';
              RestContext.response.statusCode = 500;
             // return res;                

             }
               else{
               e = new Event();
               e.Type = 'Planned Site Activity';
               e.ShowAs = 'Busy';
               e.Disable_Alarm__c = true;
               e.WhatId = accountId;
               e.Subject = subject;
               e.StartDateTime = startDateTime;
               e.EndDateTime = endDateTime;
               e.PSA_Requested_by__c = psaRequestedBy;
               e.OwnerId = UserInfo.getUserId();

            }
           }
           insert e;  
         }

           }catch(Exception ex){
               system.debug('Error in creating Event'+ex.getMessage());
           }
    }
}

Thank you in advance for the support.

1
  • 4
    Best you provide details of the "issues".
    – Keith C
    Commented Sep 18, 2019 at 13:15

1 Answer 1

1

Welcome to Salesforce StackExchange, As I understood you have facing issue with implementation logic of error handling / Response of the request.

  • I would prefer to User Database.insert() rather than Insert DML because it is partial insert the record So easy to response the record which is failing or success. Please read the documentation Database class.
  • Use RestResponse
  • I created a Response wrapper class for store the detailed info of record/failure.
  • So In try-catch block, I used Database.insert() to check if a record is successfully insert or fail with status code 200,400 with error.
  • In the catch block, I used 500 status code with error message.

So below is the sudo code

    try {
    RestResponse res = RestContext.response;
    Map < Id, Event > mapToInsert = new Map < Id, Event > ();
    List < Response > lstResponse = new List < Response > ();

    for (Database.SaveResult sr: Database.insert(mapToInsert.values(), false)) {
        String errorMsg = '';
        if (sr.isSuccess()) {
            res.statusCode = 200;
            lstResponse.add(new Response('Successfully Inserted', mapToInsert.get(sr.getId())));
        } else {
            for (Database.Error err: sr.getErrors()) {
                errorMsg = err.getStatusCode() + ': ' + err.getMessage();
            }
            res.statusCode = 400;
            lstResponse.add(new Response(errorMsg, null);
            }
        }
        res.responseBody = Blob.valueOf(JSON.serialize(lstResponse));

    } catch (Exception e) {
        RestResponse res = RestContext.response;
        res.statusCode = 500;
        res.responseBody = Blob.valueOf(JSON.serialize(new Response(e.getMessage(), null)));
    }

    public class Response {
        public String message;
        public Event eventRec;
        public Response(String message, string eventRec) {
            this.message = message;
            this.eventRec = eventRec;
        }
    }

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