Middleware for consistent, structured JSON API error responses.
dotnet add package Philiprehberger.ApiErrorStandardizerMiddleware for consistent, structured JSON API error responses.
dotnet add package Philiprehberger.ApiErrorStandardizer
Register the middleware early in your pipeline in Program.cs:
using Philiprehberger.ApiErrorStandardizer;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseErrorStandardizer();
app.MapGet("/example", () =>
{
throw new KeyNotFoundException("User not found");
});
app.Run();
When an unhandled exception is thrown, the middleware returns a structured JSON response:
{
"error": "NotFound",
"message": "User not found",
"statusCode": 404,
"traceId": "0HN4CMFQ8G5RI:00000001"
}
Map your own exception types to specific HTTP status codes:
app.UseErrorStandardizer(options =>
{
options.ExceptionStatusMap[typeof(InsufficientFundsException)] = 402;
options.ExceptionStatusMap[typeof(RateLimitException)] = 429;
options.IncludeStackTrace = false;
options.IncludeTraceId = true;
});
| Exception Type | Status Code |
|---|---|
ArgumentException | 400 Bad Request |
ArgumentNullException | 400 Bad Request |
ArgumentOutOfRangeException | 400 Bad Request |
UnauthorizedAccessException | 401 Unauthorized |
KeyNotFoundException | 404 Not Found |
InvalidOperationException | 409 Conflict |
NotImplementedException | 501 Not Implemented |
| All other exceptions | 500 Internal Server Error |
Custom mappings in ExceptionStatusMap take precedence over built-in defaults.
ApiError| Property | Type | Description |
|---|---|---|
Error | string | The error type or category |
Message | string | Human-readable error description |
StatusCode | int | HTTP status code |
TraceId | string? | Request trace identifier (if enabled) |
ValidationErrors | IDictionary<string, string[]>? | Field-level validation errors |
ErrorStandardizerOptions| Property | Type | Default | Description |
|---|---|---|---|
IncludeStackTrace | bool | false | Include stack trace in responses |
IncludeTraceId | bool | true | Include trace ID from request context |
ExceptionStatusMap | Dictionary<Type, int> | empty | Custom exception-to-status-code mappings |
ApplicationBuilderExtensions| Method | Description |
|---|---|
UseErrorStandardizer(Action<ErrorStandardizerOptions>?) | Adds the error standardizer middleware to the pipeline |
dotnet build src/Philiprehberger.ApiErrorStandardizer.csproj --configuration Release
If you find this project useful: