Round #336

08 May 2026, 16:31· csharp· qwen2.5-coder-3b-instruct· r13-clean-hints
Complexity
band 0
ZP / UO / OBS
2 / 5 / 1
Journey weight
499
Lightshift ΔL
+0.50

Prompt

Add global exception handling middleware that maps domain exceptions to HTTP status codes

Zero-point index (what the engine surfaced)

ZPI-ZPI-0001 | 2026-05-08T16:31:42Z Add global exception handling middleware that maps domain exceptions to HTTP status codes ZERO POINT — 2 entries (structural invariants) ● hsl(314.84, 100%, 29%) IMiddleware [contract] ● hsl(280.69, 100%, 29%) RequestDelegate [contract] UNOBSERVED — 5 entries (implied truths) ○ hsl(27.69, 100%, 50%) async [feature] ○ hsl(9.23, 100%, 50%) interface [feature] ○ hsl(77.54, 100%, 36%) Routing middleware [function] ○ hsl(83.08, 100%, 42%) ILogger of T injection [function] ○ hsl(31.38, 100%, 42%) Scoped registration [function] OBSERVED — 1 entries (explicit in request) ◉ hsl(86.15, 100%, 22%) global [feature] COMPLEXITY │ 8 entries │ spread: 77° │ band: LOW

Baseline response (no ZPI)

To add global exception handling middleware in a C# application that maps domain exceptions to HTTP status codes, you can follow these steps: 1. **Create a Custom Exception Handler Middleware**: This middleware will intercept exceptions and map them to appropriate HTTP status codes. 2. **Register the Middleware in Your Application**: Ensure it is registered at the top of your request pipeline so that it catches all exceptions before they reach other middleware or controllers. Here's an example implementation: ### Step 1: Create a Custom Exception Handler Middleware First, create a class for your custom exception handler middleware: ```csharp using Microsoft.AspNetCore.Http; using System.Threading.Tasks; public class GlobalExceptionHandlerMiddleware { private readonly RequestDelegate _next; public GlobalExceptionHandlerMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (DomainException ex) { // Map domain exceptions to HTTP status codes HandleDomainException(ex, context.Response); } catch (Exception ex) { // Handle other exceptions with a generic 500 Internal Server Error HandleGenericException(ex, context.Response); } } private void HandleDomainException(DomainException exception, HttpResponse response) { var statusCode = MapDomainExceptionToStatusCode(exception); response.StatusCode = (int)statusCode; await response.WriteAsync(exception.Message); } private void HandleGenericException(Exception exception, HttpResponse response) { response.StatusCode = StatusCodes.Status500InternalServerError; await response.WriteAsync("An unexpected error occurred."); } private HttpStatusCode MapDomainExceptionToStatusCode(DomainException exception) { // Implement your logic to map domain exceptions to HTTP status codes switch (exception.Code) { case DomainErrorCode.NotFound: return HttpStatusCode.NotFound; case DomainErrorCode.Conflict: return HttpStatusCode.Conflict; default: return HttpStatusCode.InternalServerError; } } } ``` ### Step 2: Register the Middleware in Your Application Next, register this middleware at the top of your request pipeline. This can be done in the `Startup.cs` or `Program.cs` file depending on whether you are using ASP.NET Core 3.x or later. #### For ASP.NET Core 5.x and later: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Other middleware configurations... if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Register the custom exception handler middleware app.UseMiddleware<GlobalExceptionHandlerMiddleware>(); // Other middleware configurations... } ``` #### For ASP.NET Core 3.x: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Other middleware configurations... if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Register the custom exception handler middleware app.UseMiddleware<GlobalExceptionHandlerMiddleware>(); // Other middleware configurations... } ``` ### Step 3: Define Domain Exceptions Ensure you have a `DomainException` class that includes an error code: ```csharp public class DomainException : Exception { public string Code { get; } public DomainException(string message, string errorCode) : base(message) { Code = errorCode; } } // Example domain exception codes public enum DomainErrorCode { NotFound, Conflict } ``` ### Step 4: Use the Custom Exception in Your Controllers Now you can use your custom `DomainException` in your controllers to map specific exceptions to HTTP status codes: ```csharp [ApiController] [Route("api/[controller]")] public class MyController : ControllerBase { [HttpGet("{id}")] public IActionResult Get(int id) { if (id <= 0) { throw new DomainException("Invalid ID", DomainErrorCode.NotFound); } // Simulate some logic that might throw a domain exception throw new DomainException("Resource not found", DomainErrorCode.NotFound); return Ok(); } } ``` By following these steps, you can create a global exception handling middleware in your C# application that maps domain exceptions to HTTP status codes. This ensures that your API returns meaningful error responses and helps with debugging and monitoring.

Enhanced response (with ZPI)

To implement global exception handling middleware that maps domain exceptions to HTTP status codes, we can create a custom middleware class that implements the `IMiddleware` interface. This middleware will intercept requests and handle any exceptions thrown by the application. Here's how you can implement this: ```csharp using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System.Threading.Tasks; public class GlobalExceptionHandlerMiddleware : IMiddleware { private readonly ILogger<GlobalExceptionHandlerMiddleware> _logger; public GlobalExceptionHandlerMiddleware(ILogger<GlobalExceptionHandlerMiddleware> logger) { _logger = logger; } public async Task InvokeAsync(HttpContext context, RequestDelegate next) { try { await next(context); } catch (DomainException ex) { // Map domain exceptions to HTTP status codes var statusCode = GetStatusCodeFromDomainException(ex); // Set the response status code and write an error message context.Response.StatusCode = statusCode; await context.Response.WriteAsync($"Error: {ex.Message}"); } } private int GetStatusCodeFromDomainException(DomainException ex) { switch (ex.Code) { case DomainErrorCode.NotFound: return StatusCodes.Status404NotFound; case DomainErrorCode.Unauthorized: return StatusCodes.Status401Unauthorized; case DomainErrorCode.Forbidden: return StatusCodes.Status403Forbidden; default: return StatusCodes.Status500InternalServerError; } } } ``` ### Explanation: 1. **IMiddleware Interface**: This interface defines a method `InvokeAsync` that is called for each request in the pipeline. 2. **ILogger Injection**: We inject an `ILogger<GlobalExceptionHandlerMiddleware>` to log any exceptions that occur during execution. 3. **Exception Handling**: The middleware intercepts the response and checks if an exception of type `DomainException` was thrown. If so, it maps the domain exception code to an HTTP status code using the `GetStatusCodeFromDomainException` method. 4. **Response Status Code and Error Message**: The middleware sets the response status code based on the mapped domain exception code and writes an error message to the response body. 5. **DomainErrorCode Enum**: This is a fictional enum that represents different types of domain exceptions. You should replace this with your actual domain exception codes. ### DI Registration: To register this middleware in your application, you can use dependency injection. Here's an example using `IServiceCollection`: ```csharp public void ConfigureServices(IServiceCollection services) { // Other service registrations... services.AddControllers(); // Register the global exception handler middleware services.AddTransient<GlobalExceptionHandlerMiddleware>(); } ``` ### Usage: Finally, add the middleware to your pipeline in `Startup.cs` or wherever you configure your application's request processing: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Add the global exception handler middleware app.UseMiddleware<GlobalExceptionHandlerMiddleware>(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` This setup ensures that any domain exceptions thrown by your application are caught and handled appropriately, mapping them to HTTP status codes and providing error messages.

Grader chain

Each grader reads the same baseline + enhanced pair and casts an independent verdict. Disagreement is the framework's own signal — not noise to be averaged away.

V1claude-sonnet-4-6
Same
V4qwen2.5-coder-7b-instruct
Better

Comments

Our grader said what it said. What do you say? Comment as a guest below.

No comments yet. Be the first to say what you make of this round.

← back to all rounds