代码之家  ›  专栏  ›  技术社区  ›  Pavel Chuchuva

Azure函数的全局异常处理程序

  •  0
  • Pavel Chuchuva  · 技术社区  · 5 年前

    是否可以为Azure函数.Net C#项目提供全局异常处理程序?

    1 回复  |  直到 5 年前
        1
  •  3
  •   George Chen    5 年前

    目前此功能不可用,您可以转到 feedback page

    但是,您仍然可以将Azure功能与Application Insights结合使用,有关详细信息,请参阅以下文档: Monitor Azure Functions

        2
  •  4
  •   Pankaj Rawat    5 年前

    我也在等待测试特性,但现在,我已经编写了日志/异常处理方面(AOP)。我有很多函数,但没有为异常处理编写一个try-catch。

    我在用 MrAdvice

    侧面

    public class LoggerAspectAttribute : Attribute, IMethodAsyncAdvice
    {
        public async Task Advise(MethodAsyncAdviceContext context)
        {
            ILog log = LogManager.GetLogger();
            RequestTelemetry requestTelemetry = new RequestTelemetry { Name = context.TargetType.Name };
            IOperationHolder<RequestTelemetry> operation = log.TelemetryClient.StartOperation(requestTelemetry);
            operation.Telemetry.Success = true;
            log.Info($"{context.TargetType.Name} trigger");
    
            try
            {
                await context.ProceedAsync(); // this calls the original method
            }
            catch (Exception ex)
            {
                operation.Telemetry.Success = false;
                log.Error(ex.Message, ex);
                throw;
            }
            finally
            {
                log.Info($"{context.TargetType.Name} completed.");
                log.TelemetryClient.StopOperation(operation);
            }
        }
    }
    

    public static class AlertFunction
    {
        [LoggerAspect]
        [FunctionName("AlertFunction")]
        public static async Task Run([EventHubTrigger("%AlertEventHub%", Connection = "AlertEventHubConnection", ConsumerGroup = "%AlertEventHubConsumerGroup%")]EventData eventMessage,
            [Inject]IEventService eventService, [Inject]ILog log)
        {
            log.Verbose($"Event PartitionKey {eventMessage.PartitionKey}, Offset {eventMessage.Offset} and SequenceNumber {eventMessage.SequenceNumber}");
            string message = Encoding.UTF8.GetString(eventMessage.GetBytes());
            log.Verbose(message);
            await eventService.FilterAlertEventAsync(message);
        }
    }
    

    希望它能给你一些建议!