Round #294

08 May 2026, 13:06· csharp· llama-3.3-70b-versatile· r13-clean-hints
Complexity
band 0
ZP / UO / OBS
2 / 5 / 1
Journey weight
494
Lightshift ΔL
+0.00

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-08T13:06:33Z Add global exception handling middleware that maps domain exceptions to HTTP status codes ZERO POINT — 2 entries (structural invariants) ● hsl(314.84, 100%, 32%) IMiddleware [contract] ● hsl(280.69, 100%, 32%) 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)

**Global Exception Handling Middleware in C#** ===================================================== To add global exception handling middleware in a C# application, you can create a custom middleware class that catches exceptions and maps them to HTTP status codes. Here's an example implementation: ### Exception Handling Middleware ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Net; using System.Threading.Tasks; 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 async Task HandleExceptionAsync(HttpContext context, Exception exception) { var statusCode = GetStatusCode(exception); var response = context.Response; response.ContentType = "application/json"; response.StatusCode = (int)statusCode; await response.WriteAsync(new ErrorDetails { StatusCode = (int)statusCode, Message = exception.Message }.ToString()); } private HttpStatusCode GetStatusCode(Exception exception) { if (exception is ArgumentException) return HttpStatusCode.BadRequest; else if (exception is InvalidOperationException) return HttpStatusCode.Conflict; else if (exception is UnauthorizedAccessException) return HttpStatusCode.Unauthorized; else if (exception is NotImplementedException) return HttpStatusCode.NotImplemented; else return HttpStatusCode.InternalServerError; } } public class ErrorDetails { public int StatusCode { get; set; } public string Message { get; set; } public override string ToString() { return $"{{ \"statusCode\": {StatusCode}, \"message\": \"{Message}\" }}"; } } ``` ### Registering the Middleware To register the exception handling middleware, add the following code to the `Startup.cs` file: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ... app.UseMiddleware<ExceptionHandlingMiddleware>(); // ... } ``` Alternatively, you can also register the middleware in the `Program.cs` file (for .NET 6 and later): ```csharp var builder = WebApplication.CreateBuilder(args); // ... var app = builder.Build(); // ... app.UseMiddleware<ExceptionHandlingMiddleware>(); // ... ``` ### Example Use Case To test the exception handling middleware, you can create a controller action that throws an exception: ```csharp [ApiController] [Route("api/[controller]")] public class ExampleController : ControllerBase { [HttpGet] public IActionResult Get() { throw new ArgumentException("Invalid argument"); } } ``` When you call the `Get` action, the exception handling middleware will catch the exception and return a JSON response with a 400 Bad Request status code: ```json { "statusCode": 400, "message": "Invalid argument" } ``` Note that you can customize the `GetStatusCode` method to map specific exceptions to different HTTP status codes. Additionally, you can modify the `ErrorDetails` class to include additional information, such as error codes or debugging information.

Enhanced response (with ZPI)

```csharp using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; // Define a custom exception handler middleware public class ExceptionHandlingMiddleware { private readonly RequestDelegate _next; private readonly ILogger<ExceptionHandlingMiddleware> _logger; public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (Exception ex) { _logger.LogError(ex, "An error occurred while processing the request"); // Map domain exceptions to HTTP status codes if (ex is ArgumentException) { context.Response.StatusCode = StatusCodes.Status400BadRequest; } else if (ex is InvalidOperationException) { context.Response.StatusCode = StatusCodes.Status403Forbidden; } else if (ex is NotFoundException) { context.Response.StatusCode = StatusCodes.Status404NotFound; } else { context.Response.StatusCode = StatusCodes.Status500InternalServerError; } // Return a JSON response with the error message await context.Response.WriteAsync(new ErrorResponse(ex.Message).ToString()); } } } // Define a custom error response class public class ErrorResponse { public string ErrorMessage { get; set; } public ErrorResponse(string errorMessage) { ErrorMessage = errorMessage; } public override string ToString() { return $"{{ \"error\": \"{ErrorMessage}\" }}"; } } // Define a custom not found exception public class NotFoundException : Exception { public NotFoundException(string message) : base(message) { } } // Register the middleware in the Startup.cs file public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ... app.UseMiddleware<ExceptionHandlingMiddleware>(); // ... } // Register the logger in the Startup.cs file public void ConfigureServices(IServiceCollection services) { services.AddLogging(logging => { logging.AddConsole(); }); services.AddScoped<ILogger<ExceptionHandlingMiddleware>, Logger<ExceptionHandlingMiddleware>>(); } ``` This implementation provides a custom exception handling middleware that maps domain exceptions to HTTP status codes. The middleware catches any exceptions that occur during the request processing pipeline and logs the error using the `ILogger` interface. It then returns a JSON response with the error message and the corresponding HTTP status code. The `ExceptionHandlingMiddleware` class is registered as a scoped service in the `Startup.cs` file, and the `ILogger` interface is injected into the middleware constructor. The `AddLogging` method is used to configure the logging settings, and the `AddScoped` method is used to register the logger as a scoped service. The `ErrorResponse` class is used to create a JSON response with the error message, and the `NotFoundException` class is a custom exception that can be thrown by the application. Note that this implementation assumes that the `NotFoundException` class is a custom exception that is thrown by the application. You can modify the implementation to handle other custom exceptions as needed.

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