Round #233
07 May 2026, 20:17· csharp· meta/llama-3.3-70b-instruct· r13-clean-hints
- Complexity
- band 0
- ZP / UO / OBS
- 2 / 5 / 1
- Journey weight
- 573
- 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-07T20:17:35Z
Add global exception handling middleware that maps domain exceptions to HTTP status codes
ZERO POINT — 2 entries (structural invariants)
● hsl(314.84, 100%, 21%) IMiddleware [contract]
● hsl(280.69, 100%, 21%) RequestDelegate [contract]
UNOBSERVED — 5 entries (implied truths)
○ hsl(27.69, 100%, 50%) async [feature]
○ hsl(9.23, 100%, 32%) interface [feature]
○ hsl(77.54, 100%, 19%) Routing middleware [function]
○ hsl(83.08, 100%, 26%) ILogger of T injection [function]
○ hsl(31.38, 100%, 40%) Scoped registration [function]
OBSERVED — 1 entries (explicit in request)
◉ hsl(86.15, 100%, 18%) 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 C# that maps domain exceptions to HTTP status codes, you can use the following approach:
### Step 1: Create a Custom Exception Class
First, create a custom exception class that will be used to handle domain exceptions. This class will inherit from the `Exception` class.
```csharp
// CustomException.cs
public class CustomException : Exception
{
public int StatusCode { get; set; }
public string ErrorMessage { get; set; }
public CustomException(int statusCode, string errorMessage)
{
StatusCode = statusCode;
ErrorMessage = errorMessage;
}
}
```
### Step 2: Create a Middleware Class
Next, create a middleware class that will handle exceptions and map them to HTTP status codes.
```csharp
// ExceptionHandlingMiddleware.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Builder;
using System.Threading.Tasks;
using System;
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
public ExceptionHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (CustomException ex)
{
await HandleExceptionAsync(context, ex);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var statusCode = GetStatusCode(exception);
var errorMessage = GetErrorMessage(exception);
context.Response.ContentType = "application/json";
context.Response.StatusCode = statusCode;
await context.Response.WriteAsync(new ErrorDetails
{
StatusCode = statusCode,
ErrorMessage = errorMessage
}.ToString());
}
private int GetStatusCode(Exception exception)
{
if (exception is CustomException customException)
{
return customException.StatusCode;
}
return StatusCodes.Status500InternalServerError;
}
private string GetErrorMessage(Exception exception)
{
if (exception is CustomException customException)
{
return customException.ErrorMessage;
}
return "An error occurred while processing your request.";
}
}
public class ErrorDetails
{
public int StatusCode { get; set; }
public string ErrorMessage { get; set; }
public override string ToString()
{
return $"{{ \"statusCode\": {StatusCode}, \"errorMessage\": \"{ErrorMessage}\" }}";
}
}
```
### Step 3: Register the Middleware
Finally, register the middleware in the `Startup.cs` file.
```csharp
// Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<ExceptionHandlingMiddleware>();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
```
### Example Use Case
To use the custom exception, throw it in your controller action.
```csharp
// MyController.cs
using Microsoft.AspNetCore.Mvc;
using System;
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
throw new CustomException(404, "Resource not found.");
}
}
```
In this example, when the `Get` action is called, it will throw a `CustomException` with a status code of 404 and an error message of "Resource not found.". The exception handling middleware will catch this exception and return a JSON response with the specified status code and error message.
**Mapping Domain Exceptions to HTTP Status Codes**
-----------------------------------------------
To map domain exceptions to HTTP status codes, you can create a dictionary that maps exception types to status codes.
```csharp
// ExceptionMapper.cs
using System;
using System.Collections.Generic;
public class ExceptionMapper
{
private readonly Dictionary<Type, int> _exceptionMap;
public ExceptionMapper()
{
_exceptionMap = new Dictionary<Type, int>
{
{ typeof(NotFoundException), 404 },
{ typeof(ValidationException), 400 },
{ typeof(AuthorizationException), 401 },
{ typeof(ForbiddenException), 403 }
};
}
public int GetStatusCode(Exception exception)
{
if (_exceptionMap.TryGetValue(exception.GetType(), out int statusCode))
{
return statusCode;
}
return StatusCodes.Status500InternalServerError;
}
}
```
You can then use this exception mapper in your exception handling middleware to map domain exceptions to HTTP status codes.
```csharp
// ExceptionHandlingMiddleware.cs
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var statusCode = _exceptionMapper.GetStatusCode(exception);
var errorMessage = GetErrorMessage(exception);
context.Response.ContentType = "application/json";
context.Response.StatusCode = statusCode;
await context.Response.WriteAsync(new ErrorDetails
{
StatusCode = statusCode
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 occurred");
context.Response.StatusCode = ex.StatusCode;
await context.Response.WriteAsync(ex.Message);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected exception occurred");
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 is registered in the DI container using the `AddExceptionHandlingMiddleware` method and used in the application pipeline using the `UseExceptionHandlingMiddleware` method.
The `ExceptionHandlingMiddleware` class defines the `InvokeAsync` method, which is called for each incoming request. This method tries to call the next middleware in the pipeline using the `_next` delegate. If a domain exception is thrown, it logs the exception using the `ILogger` instance and sets the HTTP status code and response body accordingly. If an unexpected exception is thrown, it logs the exception and sets the HTTP status code to 500.
The `DomainException` class defines a custom exception class for domain exceptions, which has a `StatusCode` property that maps to the corresponding HTTP status code. The `NotFoundException` and `BadRequestException` classes are custom exception classes that inherit from `DomainException` and have specific status codes.
In the example usage, the `Program` class defines a route that throws a `NotFoundException` when accessed. The exception handling middleware catches this exception and sets the HTTP status code to 404 and the response body to the exception message.
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-haiku-4-5-20251001
BetterV4qwen2.5-coder-7b-instruct
BetterComments
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.