Round #293

08 May 2026, 13:06· csharp· meta/llama-3.3-70b-instruct· 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.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.StatusCode = statusCode; response.ContentType = "application/json"; var errorResponse = new ErrorResponse { StatusCode = statusCode, Message = exception.Message }; await response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(errorResponse)); } private int GetStatusCode(Exception exception) { // Map domain exceptions to HTTP status codes if (exception is ValidationException) return StatusCodes.Status400BadRequest; else if (exception is NotFoundException) return StatusCodes.Status404NotFound; else if (exception is UnauthorizedException) return StatusCodes.Status401Unauthorized; else return StatusCodes.Status500InternalServerError; } } public class ErrorResponse { public int StatusCode { get; set; } public string Message { get; set; } } public class ValidationException : Exception { public ValidationException(string message) : base(message) { } } public class NotFoundException : Exception { public NotFoundException(string message) : base(message) { } } public class UnauthorizedException : Exception { public UnauthorizedException(string message) : base(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 use the `app.UseExceptionHandler` method to register the middleware: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ... app.UseExceptionHandler(appBuilder => { appBuilder.Run(async context => { var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>(); var exception = exceptionHandlerPathFeature.Error; await HandleExceptionAsync(context, exception); }); }); // ... } ``` ### Example Use Cases Here are some example use cases for the exception handling middleware: * **Validation Exception**: Throw a `ValidationException` when a user provides invalid input data. ```csharp public class UserController : Controller { [HttpPost] public IActionResult CreateUser([FromBody] CreateUserRequest request) { if (string.IsNullOrEmpty(request.Name)) { throw new ValidationException("Name is required"); } // Create user logic return Ok(); } } ``` * **Not Found Exception**: Throw a `NotFoundException` when a user requests a non-existent resource. ```csharp public class ProductController : Controller { [HttpGet("{id}")] public IActionResult GetProduct(int id) { var product = _productService.GetProduct(id); if (product == null) { throw new NotFoundException("Product not found"); } return Ok(product); } } ``` * **Unauthorized Exception**: Throw an `UnauthorizedException` when a user attempts to access a protected resource without proper authentication. ```csharp public class ProtectedController : Controller { [Authorize] [HttpGet] public IActionResult GetProtectedData() { if (!User.Identity.IsAuthenticated) { throw new UnauthorizedException("Unauthorized access"); } // Return protected data return Ok(); } } ``` By using the exception handling middleware, you can catch and handle exceptions in a centralized manner, providing a better user experience and more informative error messages.

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 class for domain exceptions public class DomainException : Exception { public int StatusCode { get; set; } public DomainException(int statusCode, string message) : base(message) { StatusCode = statusCode; } } // Define a custom exception class for not found exceptions public class NotFoundException : DomainException { public NotFoundException(string message) : base(404, message) { } } // Define a custom exception class for bad request exceptions public class BadRequestException : DomainException { public BadRequestException(string message) : base(400, message) { } } // Define the exception handling 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 (DomainException ex) { _logger.LogError(ex, $"Domain exception: {ex.Message}"); context.Response.StatusCode = ex.StatusCode; await context.Response.WriteAsync(ex.Message); } catch (Exception ex) { _logger.LogError(ex, $"Unexpected exception: {ex.Message}"); context.Response.StatusCode = 500; await context.Response.WriteAsync("Internal server error"); } } } // Register the exception handling middleware in the DI container public static class ExceptionHandlingMiddlewareExtensions { public static void AddExceptionHandlingMiddleware(this IServiceCollection services) { services.AddTransient<ExceptionHandlingMiddleware>(); } public static IApplicationBuilder UseExceptionHandlingMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<ExceptionHandlingMiddleware>(); } } // Example usage: public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Register the exception handling middleware builder.Services.AddExceptionHandlingMiddleware(); var app = builder.Build(); // Use the exception handling middleware app.UseExceptionHandlingMiddleware(); // Define a route that throws a domain exception app.MapGet("/throw-exception", async (HttpContext context) => { throw new NotFoundException("Resource not found"); }); app.Run(); } } ``` This implementation defines a custom exception handling middleware that catches domain exceptions and maps them to HTTP status codes. The middleware also logs the exceptions using the `ILogger` interface. The `ExceptionHandlingMiddleware` class takes a `RequestDelegate` and an `ILogger` instance in its constructor. The `InvokeAsync` method is called for each incoming request, and it tries to execute the next middleware in the pipeline. If a domain exception is thrown, it catches the exception, logs it, and sets the HTTP status code accordingly. If an unexpected exception is thrown, it logs the exception and sets the HTTP status code to 500. The `AddExceptionHandlingMiddleware` method registers the exception handling middleware in the DI container, and the `UseExceptionHandlingMiddleware` method adds the middleware to the pipeline. In the example usage, the `Program` class registers the exception handling middleware and defines a route that throws a `NotFoundException`. When a request is made to this route, the exception handling middleware catches the exception, logs it, and sets the HTTP status code to 404.

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