如何正常使Service Bus触发的Azure功能失败

时间:2016-10-08 17:50:28

标签: c# azure azureservicebus azure-servicebus-queues azure-functions

我想使用Azure Functions根据队列消息调用REST端点。 Documentation告诉我......

  

函数运行时以PeekLock模式接收消息,如果函数成功完成,则在消息上调用Complete;如果函数失败,则调用Abandon。

因此,当REST调用失败时,我尝试通过抛出异常让主机放弃该消息来使函数失败。

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

有没有人知道更好的方法来优雅地使功能失败?

1 个答案:

答案 0 :(得分:2)

记录失败并手动致电message.Abandon()

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