CodexBloom - Programming Q&A Platform

How to Handle Multiple handling Types in ASP.NET Core Global handling Handler?

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-07-05
asp.net-core exception-handling middleware C#

Quick question that's been bugging me - I'm having a hard time understanding After trying multiple solutions online, I still can't figure this out... Quick question that's been bugging me - I'm trying to implement a global exception handler in my ASP.NET Core application to return user-friendly behavior messages. However, I'm running into issues when trying to differentiate between different types of exceptions. For example, I want to log validation errors differently from unexpected server errors, but my current implementation isn't working as expected. I've set up a middleware to catch exceptions 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"; // The following line is where I struggle return context.Response.WriteAsync(new ProblemDetails { Title = "An behavior occurred", Detail = ex.Message, Status = (int)HttpStatusCode.InternalServerError }.ToString()); } } ``` I've registered this middleware in `Startup.cs` like so: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseMiddleware<ExceptionHandlingMiddleware>(); // other middlewares } ``` The question arises when I throw different types of exceptions, such as `ValidationException` or a custom exception. They all seem to return the same generic behavior response, which is not what I want. I tried using `is` to check the type of exception, but it seems like none of my conditions are hitting. Here’s what I added: ```csharp private Task HandleExceptionAsync(HttpContext context, Exception ex) { context.Response.ContentType = "application/json"; ProblemDetails problemDetails; if (ex is ValidationException) { problemDetails = new ProblemDetails { Title = "Validation behavior", Detail = ex.Message, Status = (int)HttpStatusCode.BadRequest }; } else { problemDetails = new ProblemDetails { Title = "An behavior occurred", Detail = ex.Message, Status = (int)HttpStatusCode.InternalServerError }; } return context.Response.WriteAsync(problemDetails.ToString()); } ``` Despite this, I still see the same message for all exceptions. I’ve confirmed that the exceptions are indeed being thrown, and I even added logging to verify their types before reaching the middleware. Can anyone guide to understand how to differentiate and handle these exceptions correctly? What am I missing? I'd really appreciate any guidance on this. My development environment is Linux. What's the best practice here? For reference, this is a production desktop app. I'm working on a REST API that needs to handle this. I'm on CentOS using the latest version of C#. What would be the recommended way to handle this?