Round #337

08 May 2026, 16:36· 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:36:19Z 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 downstream handlers. 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 takes an `HttpContext` and a `RequestDelegate`. The middleware can intercept the request, modify it, or handle exceptions. 2. **ILogger Injection**: We inject an `ILogger<GlobalExceptionHandlerMiddleware>` to log any errors that occur during execution. 3. **Exception Handling**: In the `InvokeAsync` method, we attempt to execute the next middleware in the pipeline using `await next(context)`. If an exception of type `DomainException` is caught, we map it to an appropriate HTTP status code using the `GetStatusCodeFromDomainException` method. 4. **Error Response**: We set the response status code and write an error message to the response body. 5. **DomainErrorCode Mapping**: The `GetStatusCodeFromDomainException` method maps specific domain exception codes to HTTP status codes. This allows for a clear mapping of business logic errors to HTTP responses. ### DI Registration: To register this middleware in your application, you can use dependency injection. Here's an example using ASP.NET Core's built-in services: ```csharp public void ConfigureServices(IServiceCollection services) { // Other service registrations... services.AddControllers(); // Register the global exception handler middleware services.AddTransient<GlobalExceptionHandlerMiddleware>(); } ``` Then, in your `Startup.cs` or equivalent file, configure the middleware pipeline to use this custom middleware: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Use the global exception handler middleware app.UseMiddleware<GlobalExceptionHandlerMiddleware>(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` This setup ensures that any exceptions thrown by your controllers or other middleware will be caught and handled appropriately, mapping domain-specific errors to HTTP status codes.

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