[英]Catch Async Method exception in Azure function
我已經使用C#(庫項目)和Aspect(AOP)進行日志記錄來編寫Azure函數v1。 我在catch塊中沒有異常。
我有上面討論的相同問題,但是,Azure Function Run方法是異步任務,其異常處理與異步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");
}
}
記錄儀方面(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() ”調用async方法時,它可以工作。
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()方法可能導致死鎖問題,應避免使用async / await 。
我的職能每天處理數百萬個事件。 如果這是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...");
}
}
}
編輯 :是的,它與Advice先生一起工作:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.