Hi Vadivu s Dharani,
Welcome to the Microsoft Q&A Platform! Thank you for reaching out regarding your query on rollback the transaction of API from Azure function.
By looking at the code shared, you are using TransactionScope inside Azure Function and calling the API.
You want to roll back the transaction of API from Azure function which is not possible directly by using TransactionScope because to handle transaction rollbacks in an Azure Function, you can use the TransactionScope class, as you've done in your code. However, it's important to note that TransactionScope works well with databases that support distributed transactions, but it might not directly roll back changes made by an external API.
To achieve rollback behavior when calling an external API, you need to implement compensating actions manually.
Here is the updated code you might consider:
using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
try
{
// Your existing Azure Function code here.
// Call the API
var response = await CallApiAsync(receivedData);
if (!response.IsSuccessStatusCode)
{
throw new Exception("API call failed.");
}
// Simulate an error
int x = 0;
int y = 5;
int z = 5 / 0; // This will throw an exception
scope.Complete();
}
catch (Exception ex)
{
_logger.LogError("An exception occurred: {exception}", ex);
// Call a compensating transaction to undo the API changes
await CallApiUndoAsync(receivedData);
}
}
If this answers your query, do click Accept Answer
and Yes
for was this answer helpful. And, if you have any further query do let us know.