Where to catch exceptions in an asynchronous Azure function

use*_*050 2 c# asynchronous exception-handling azure azure-functions

I've set up an Azure function and I want it to run asynchronously because I expect to have hundreds/thousands/more messages in my queue that will all get dequeued at the same time, so I've implemented it as such below (maybe there's a better way). Or do I need to worry about running code in the functions asynchronously?

Will Azure handle thousands of these functions run at the same time, if thousands of messages in the queue are all dequeued at once? This Azure function article says only a few hundred can run at once

Where is the best place to put the try catch statement? Inside the asynchronous call around my logic or outside the asynchronous call like my code? Or does it matter?

public static class CancelEvent
{
    [FunctionName("CancelEvent")] 
    public static async void RunAsync([ServiceBusTrigger("canceleventqueue", AccessRights.Manage, Connection = "service_bus_key")]string myQueueItem, TraceWriter log, ExecutionContext context)
    {
        try
        {
            await Task.Run(() => Processor.ProcessAsync());
        }
        catch(Exception ex)
        {
        }
     }
}

public class Processor
{
    public static void ProcessAsync()
    {
        // do the work
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

TLDR;不要将 Azure Functions 构建为异步的。

在我最近使用 azure 函数的经验中,我发现最好不要将我的函数构建为异步函数。

在我的情况下,我使用 ServiceBusTrigger 接收消息,然后等待处理方法,并且感到困惑的是,当冒泡异常时,它不会在 azure 门户中显示为失败,也不会捕获异常详细信息在 Application Insights 帐户中,它也不会正确地放弃或死信消息。我只会通过转到存储帐户中的 files\eventlog.xml 部分来发现异常详细信息,在那里我会发现有关未处理的异常使函数陷入困境的投诉。

经过一天的尝试/捕获和处理 message.Abandon() 和 message.Deadletter() 逻辑以及手动记录所有 AppInsights 遥测,我发现根本不做异步和冒泡他的异常(在第一次执行错误报告或处理逻辑之后)导致了我期望的平台之外的所有行为。

门户中函数的“运行历史”正确显示了通过和失败的执行,并捕获了所有异常详细信息。

这是保持 Azure 函数静态、同步和简单的警示故事。他们设计的消息处理特性应该已经足够异步了。