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?