Global exception handler for Azure Functions

I'm also waiting for test feature but for now, I have written my aspect (AOP) for logging/Exception handling. I have many functions but didn't write single try-catch for exception handling.

I'm using MrAdvice for AOP

Aspect

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);
        }
    }
}

Function

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);
    }
}

hope it will give some idea!


For now this feature is not available, you could go to the feedback page upvote the feature to indicate your request.

However you still could use Azure Function with Application Insights, about details you could refer to this doc: Monitor Azure Functions.


It is possible now with the new out-of-process (= isolated) model by defining your own middleware. Here, in the "samples" folder of the "azure-functions-dotnet-worker" repository, I also found a sample for ExceptionHandlingMiddleware.

Unfortunately, related content is too big to include it in the answer, but I hope I put enough keywords to find the thing.