Kai Walter Kai Walter - 1 month ago 17
C# Question

How do I gracefully fail a Service Bus triggered Azure Function

I want to use Azure Functions to call REST endpoints based on Queue messages.
Documentation tells me ...


The Functions runtime receives a message in PeekLock mode and calls Complete on the message if the function finishes successfully, or calls Abandon if the function fails.


Hence I try to fail the function by throwing an exception for the host to abandon the message when the REST call fails.

using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.ServiceBus.Messaging;

public static void Run(BrokeredMessage message, TraceWriter log)
{
string body = message.GetBody<string>();

using (var client = new HttpClient())
{
var content = new StringContent(body, Encoding.UTF8, "application/json");
var response = client.PutAsync("http://some-rest-endpoint.url/api", content).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception("Message could not be sent");
}
}
}


Does anyone know a better way to gracefully fail the function?

Answer

Log the failure and call message.Abandon() manually

public static async Task RunAsync(BrokeredMessage message, TraceWriter log) {
    var body = message.GetBody<string>();

    using (var client = new HttpClient()) {
        var content = new StringContent(body, Encoding.UTF8, "application/json");
        var response = await client.PutAsync("http://some-rest-endpoint.url/api", content);
        if (!response.IsSuccessStatusCode) {
            log.Warning("Message could not be sent");
            await message.AbandonAsync();
        }
    }    
}