Hi,
I am making callout to external system to get records out of 100 2 failed i want to retry those failed records till 3 time. Can someone help with code?
#Integration #Salesforce Developer
To handle retry logic in Apex for callouts (like retrying 2 failed records up to 3 times), you can use Queueable Apex with the Database.AllowsCallouts interface combined with custom exception handling or tracking failed record IDs. Try the following.
public class IntegrationRetryQueueable implements Queueable, Database.AllowsCallouts {
private List<Id> recordIds;
private Integer retryCount;
public IntegrationRetryQueueable(List<Id> recordIds, Integer retryCount) {
this.recordIds = recordIds;
this.retryCount = retryCount;
}
public void execute(QueueableContext context) {
List<Id> failedRecords = new List<Id>();
for (Id recId : recordIds) {
try {
// Perform your external callout logic here for recId
HttpResponse response = makeCallout(recId);
if (response.getStatusCode() != 200) {
failedRecords.add(recId);
}
} catch (Exception e) {
// Catch connection timeouts or callout exceptions
failedRecords.add(recId);
}
}
// If there are failures and we haven't hit the 3-attempt limit, chain the job
if (!failedRecords.isEmpty() && retryCount < 3) {
if (!Test.isRunningTest()) {
System.enqueueJob(new IntegrationRetryQueueable(failedRecords, retryCount + 1));
}
}
}
private HttpResponse makeCallout(Id recId) {
// Implement your HttpRequest and Http send logic here
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.yourtargetsystem.com/endpoint');
req.setMethod('POST');
// Set body based on recId...
return h.send(req);
}
}