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.