如何优雅地使服务总线触发 Azure 函数失败
How do I gracefully fail a Service Bus triggered Azure Function
我想使用 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();
}
}
}
我想使用 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();
}
}
}