Kai Walter
Kai Walter

Reputation: 4001

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?

Upvotes: 2

Views: 3078

Answers (1)

Nkosi
Nkosi

Reputation: 247018

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();
        }
    }    
}

Upvotes: 2

Related Questions