我已经使用C#(库项目)和Aspect(AOP)编写了Azure函数v1用于日志记录。我在catch块中没有得到异常。
捕获异步方法引发的异常
我有上面讨论的相同问题,但Azure函数运行方法是异步任务,其异常处理和异步void相同。不确定哪里有问题?假设这是函数SDK问题。
Azure函数
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");
}
}
记录器方面
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函数中删除异步等待并通过“getWaiter().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()方法可能导致死锁问题,应避免使用异步/等待。
我的函数每天处理数百万个事件。如果这是FunctionSDK问题或其他问题,这是正确的解决方案吗?
您需要编写异步建议,例如:
public class LoggerAspectAttribute : Attribute, IMethodAsyncAdvice
{
public async Task Advise(MethodAsyncAdviceContext context)
{
//Logger initilizer here
Console.WriteLine($"{context.TargetType.Name} started...");
try
{
await context.ProceedAsync(); // this calls the original method
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine($"{context.TargetType.Name} completed...");
}
}
}
编辑:是的,它适用于Mr建议:)