在Azure函数中捕获异步方法异常

时间:2019-01-08 06:57:36

标签: c# azure async-await azure-functions

我已经使用C#(库项目)和用于日志的Aspect(AOP)编写了Azure函数v1。我在catch块中没有异常。

Catch an exception thrown by an async method

我有上面讨论的相同问题,但是,Azure Function Run方法是异步任务,其异常处理与异步void相同。不知道哪里出了问题?假设这是功能SDK问题。

天蓝色功能

public static class PingFunction
{
    [LoggerAspect]
    [FunctionName("PingFunction")]
    public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
    {
        string name = string.Empty;
        log.Info("C# HTTP trigger function processed a request.");

            SomeService someService = new SomeService();
            await someService.DoSomething();

        return req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
    }
}

public class SomeService
{
    public async Task DoSomething()
    {
        await Task.Delay(1000);
        throw new Exception("Exception from Service");
    }
}

记录器方面(MrAdvise)

public class LoggerAspectAttribute : Attribute, IMethodAdvice
{
    public void Advise(MethodAdviceContext context)
    {
        //Logger initilizer here
        Console.WriteLine($"{context.TargetType.Name} started...");
        try
        {
            context.Proceed(); // this calls the original method
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            Console.WriteLine($"{context.TargetType.Name} completed...");
        }
    }
}

解决方法 当我从Azure函数中删除Async-await并通过“ GetAwaiter()。GetResult()”调用异步方法时,它将起作用。

public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
    {
        string name = string.Empty;
        log.Info("C# HTTP trigger function processed a request.");

        SomeService someService = new SomeService();
        someService.DoSomething().GetAwaiter().GetResult();

        return req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
    }

Task.GetAwaiter().GetResult() methods cause the potential for deadlock issues and should be avoided in favor of async/await

我的函数每天处理数百万个事件。如果这是FunctionSDK问题或其他问题,这是正确的解决方案吗?

1 个答案:

答案 0 :(得分:0)

您需要编写一个异步建议,例如:

User

编辑:是的,它与Advice先生一起使用:)