Home > Blockchain >  Azure .net 5 isolated functions: Using middleware to catch exceptions
Azure .net 5 isolated functions: Using middleware to catch exceptions

Time:11-09

As the title says, I'm trying to handle Exceptions in my Azure functions middleware. It should be possible according to some articles, but I've not managed to make their code work for me. I've also checked the docs but that didn't handle Exception handling.

My Code (also on Github):

Program.cs:

using Microsoft.Extensions.Hosting;

namespace MiddleWareTest
{
    public class Program
    {
        public static void Main()
        {
            var host = new HostBuilder()
                .ConfigureFunctionsWorkerDefaults(
                    builder =>
                    {
                        builder.UseMiddleware<ExceptionLoggingMiddleware>();
                    }
                )
                .Build();

            host.Run();
        }
    }
}

ExceptionLoggingMiddleware.cs:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Middleware;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

namespace MiddleWareTest
{
    public class ExceptionLoggingMiddleware : IFunctionsWorkerMiddleware
    {
        public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                var logger = context.GetLogger(context.FunctionDefinition.Name);
                logger.LogError("Unexpected Error in {0}: {1}", context.FunctionDefinition.Name, ex.Message);
            }
        }
    }
}

Function1.cs

using System;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;

namespace MiddleWareTest
{
    public class Function1
    {
        [Function("Function1")]
        public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
            FunctionContext context)
        {
            throw new Exception("yo");
        }
    }
}

To my understanding this code should suffice to handle Exceptions, but whenever I execute Function1, the exception does not get handled by my Middleware, it's uncaught.

My question:

What am I missing/doing wrong in order to implement Exception handling in my Azure Functions Middleware?

Thanks in advance.

CodePudding user response:

Thank you Andy for your suggestions, We believe the issue has been fixed as a result of the discussions in the comments, thus we are turning the above comments to an Answer for this thread to assist other community members.

As you may have seen, the issue is that you are using an outdated version of Microsoft.Azure.Functions.Worker updating to the lastest version from your Nuget package manager fixed your issue.

  • Related