Forum Discussion
Why is element in the queue deleted even if the function throws an exception?
I write an Azure Function with a queue trigger and i want to send the data to the backend service if the backend service is avaiable and if not available then the element should still be in the queue.
My question is how can i achieve this?
my code and host.json looks like this ?
[Function("QueueCancellations")]
public async Task<IActionResult> QueueCancellation([QueueTrigger("requests", Connection = "ConnectionStrings:QUEUE_CONNECTION_STRING")] string message)
{
try
{
using (var httpClient = new HttpClient())
{
var content = new StringContent(message, Encoding.UTF8, "application/json");
var httpResponse = await httpClient.PostAsync(_configuration["LOCAL_SERVICE_URL_CANCELL"], content);
if (httpResponse.IsSuccessStatusCode)
{
return new OkObjectResult("Data sent to backend");
}
else
{
return new BadRequestObjectResult("Backend not available");
}
}
}
catch (Exception ex) {
_logger.LogError(ex.Message);
return new BadRequestObjectResult("Backend not available");
}
}
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": false,
"excludedTypes": "Request"
},
"enableLiveMetricsFilters": true
}
},
"logLevel": {
"default": "Information",
"Host.Results": "Information",
"functions": "Information",
"Host.Aggregator": "Information"
},
"extensions": {
"queues": {
"maxPollingInterval": "00:00:02",
"visibilityTimeout": "00:00:30",
"batchSize": 16,
"maxDequeueCount": 5,
"newBatchThreshold": 8,
"messageEncoding": "base64"
}
}
}
How about try this?
[Function("QueueCancellations")]
public async Task QueueCancellation([QueueTrigger("requests", Connection = "ConnectionStrings:QUEUE_CONNECTION_STRING")] string message)
{
try
{
using (var httpClient = new HttpClient())
{
var content = new StringContent(message, Encoding.UTF8, "application/json");
var httpResponse = await httpClient.PostAsync(_configuration["LOCAL_SERVICE_URL_CANCELL"], content);if (httpResponse.IsSuccessStatusCode)
{
_logger.LogInformation("Data sent to backend successfully.");
}
else
{
_logger.LogWarning("Backend not available, retrying...");
throw new Exception("Backend not available");
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error sending data to backend, retrying...");
throw; // This will cause the message to be retried
}
}