1

My triger code is

trigger sendMessage on Message__c (before insert) {
    //retrieve contact info of selected contact--------------------
    sObject contact = [Select Name, Phone, Title, MobilePhone from Contact WHERE Id =:Trigger.new[0].Contact_Mobile__c];

    String data = '{"contactInfo":'+JSON.serialize(contact)+',"message":"'+Trigger.new[0].Text_Message__c+'"}';    

    //sendMessageOnTrigger sendMessage = new sendMessageOnTrigger();
    sendMessageOnTrigger.sendMessage(data);

}

My class code which contains future method

public with sharing class sendMessageOnTrigger {

    @future(callout=true)
    public static void sendMessage(String data){              

        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('http://twil-smsapp.herokuapp.com/api/sendSms');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        // Set the body as a JSON object
        request.setBody(data);
        HttpResponse response = http.send(request);
        System.debug('-------------------------------------->');                
        // Parse the JSON response
        if (response.getStatusCode() != 200) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
            //Trigger.new[0].Text_Message__c.addError('Unable to send message!!, please try again later.');
            //ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Oops, something went wrong!!'));
        } else {
            //ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'Message sent successfully!'));
            System.debug(response.getBody());
            Map<String, Object> json =
                (Map<String, Object>)
                    JSON.deserializeUntyped(response.getBody());
            if(json.get('responseCode') != 200) {
                //change trigger data here if response is not expected so that insert operation will stop and generate an errror
    //Trigger.new[0].Text_Message__c.addError('Unable to send message!!, please try again later.');
            } 
        }
        System.debug('<--------------------------------------');
    }
}

I want to modify the trigger data in future method which has a http request to stop the insert operation if the api http request is not correct. For that, I will be using Trigger.new[0].Text_Message__c.addError('Unable to send message!!, please try again later.');. How can we achieve this?

1
  • Trigger will run as first and commit data in the database. You future method will run after 10 secs or 10 minutes, so there is no way you can stop that insert from happening . Commented Apr 12, 2018 at 12:29

1 Answer 1

3

You cannot, in your trigger, surface errors that take place in a future method, because the future method executes in a different transaction. There's no way to communicate back to the trigger from that context.

However, your future method can modify the Message__c objects - its changes just won't propagate back to the trigger. If you are initiating these message sends from a Visualforce or Lightning page, your page can poll the inserted objects for a status message you write there.

That said, I am skeptical of the design here. If, again, you are initiating the sending of these messages from a user interface, why not make the callouts from the UI controller side? You can then handle any errors appropriately before writing an object into the database, if you need to do so.

5
  • how can we trigger callout from the ui ? so that on response of it we can decide if the normal execution should continue like storing into database. i followed this method because it was the easiest just a trigger when ever something is stored in message object from anywhere and callout will be made. please suggest. @David Reed Commented Apr 12, 2018 at 18:28
  • That is too big a topic for a comment thread, @NilkamalGotarne. But you can certainly perform callouts in multiple ways from both Visualforce and Lightning user experiences.
    – David Reed
    Commented Apr 12, 2018 at 19:02
  • 7 actually i am doing it by both ways. i am able to achieve it using visual force. if could just point me in right direction it would save time for me. Thank you for your help Commented Apr 13, 2018 at 2:56
  • also whwn entry is made into message. how to get geberated messaged record;s id? Commented Apr 13, 2018 at 12:22
  • @NilkamalGotarne, if you have further questions, please ask a new question - comment threads are not good for follow ups.
    – David Reed
    Commented Apr 13, 2018 at 12:50

You must log in to answer this question.

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