CodexBloom - Programming Q&A Platform

C# 10 - implementing Custom handling Handling in Middleware for ASP.NET Core

👀 Views: 60 💬 Answers: 1 📅 Created: 2025-06-11
asp.net-core middleware exception-handling C#

I'm performance testing and Hey everyone, I'm running into an issue that's driving me crazy... I'm currently developing an ASP.NET Core application and have implemented a custom middleware for handling exceptions globally. However, I'm working with issues where certain exceptions are not being caught, leading to unhandled exceptions and 500 Internal Server Errors. My middleware looks like this: ```csharp public class ExceptionHandlingMiddleware { private readonly RequestDelegate _next; public ExceptionHandlingMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } private Task HandleExceptionAsync(HttpContext context, Exception ex) { context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; return context.Response.WriteAsync(new { StatusCode = context.Response.StatusCode, Message = "Internal Server behavior", Detail = ex.Message }.ToString()); } } ``` I have registered this middleware in the `Configure` method of `Startup.cs` like this: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseMiddleware<ExceptionHandlingMiddleware>(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` The scenario arises when I throw a `DbUpdateException` from my controller, and instead of being caught by my middleware, it results in a 500 behavior without invoking the `HandleExceptionAsync` method. I’ve verified that the exception is thrown inside the `await` call in the middleware. I've also tried wrapping the `await` statement in a `try-catch` block directly in the controller action, but the middleware still fails to capture it. I'm using ASP.NET Core 6.0. What could be causing this behavior, and how can I ensure that all exceptions, including those from Entity Framework, are properly caught and handled by my middleware? Am I missing something obvious? Any feedback is welcome!