CodexBloom - Programming Q&A Platform

Error Handling with Custom Middleware in ASP.NET Core 6 - UnhandledExceptionMiddleware not logging exceptions

๐Ÿ‘€ Views: 43 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-24
asp.net-core middleware exception-handling C#

I'm learning this framework and I'm learning this framework and I've been working on this all day and I'm currently working on an ASP.NET Core 6 application, and I've implemented custom middleware to handle exceptions globally and log them..... However, it seems that my middleware isn't catching exceptions as expected. Hereโ€™s how my middleware is set up: ```csharp public class UnhandledExceptionMiddleware { private readonly RequestDelegate _next; private readonly ILogger<UnhandledExceptionMiddleware> _logger; public UnhandledExceptionMiddleware(RequestDelegate next, ILogger<UnhandledExceptionMiddleware> logger) { _next = next; _logger = logger; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { _logger.LogError(ex, "An unhandled exception occurred."); context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; await context.Response.WriteAsync("An internal server error occurred."); } } } ``` I've registered the middleware in the `Startup.cs` file like this: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseMiddleware<UnhandledExceptionMiddleware>(); // other middlewares app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` Despite this setup, when I throw an exception in my controller: ```csharp [HttpGet] public IActionResult Get() { throw new InvalidOperationException("Test exception"); } ``` The application just returns a default error page instead of logging the exception. I've checked that the logging configuration is properly set, and I'm using `Serilog` for logging to a file. I'm not seeing any entries in the log file when the exception occurs, which makes me think the middleware isn't executing at all. I also tried placing the middleware after `UseRouting()` and before `UseEndpoints()`, but it didn't help. What am I missing here? Are there specific scenarios where middleware doesnโ€™t catch exceptions? Any insights into this behavior would be greatly appreciated! I'm using C# 3.9 in this project. I'm coming from a different tech stack and learning C#. This is for a microservice running on Windows 10.