c# - 如何优雅地使服务总线触发 Azure Functions 失败

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

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

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.

因此,当 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");
        }
    }    
}

有人知道更好的方法来优雅地失败该函数吗?

最佳答案

记录失败并手动调用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();
        }
    }    
}

关于c# - 如何优雅地使服务总线触发 Azure Functions 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39935491/

相关文章:

xml - 来自服务总线代理消息的未知 xml 序列化内容/命名空间

azure - 从 Service Bus Java 客户端一次性删除所有消息

c# - 非常慢的 WebResponse 触发超时

sql-server - 为什么我的 Azure SQL 数据库索引仍然碎片?

azure - 有没有办法在 TFS 服务 Web Hook 事件失败或 Web Hook 状态发生任何变化时设置通知

c# - Azure WebJobs 和 ServiceBusTrigger

c# - 创建对特定 RID 的另一个项目的 NET Core 项目引用

c# - 尝试发送电子邮件时为 "The operation has timed out"

c# - ObservableCollection 以及存储库

asp.net-mvc - 将 ASP.NET 应用程序部署到 Azure Web 应用程序时出现 HTTP 403 错误