This package provides a robust and extensible framework for centralized exception handling in .NET Web APIs. It standardizes error responses using ProblemDetails, supports custom exceptions and includes a flexible status code mapping system. The package integrates seamlessly via middleware and service configuration, making global error handling clean and maintainable.
IStatusCodeMapper
An interface to decouple the logic of mapping exceptions to HTTP status codes. Makes it easy to extend or override.
StatusCodeMapper
Default implementation of IStatusCodeMapper, handling common .NET exceptions like ArgumentException, UnauthorizedAccessException and NotImplementedException.
ExceptionHandler
Implements IExceptionHandler from ASP.NET Core. This service:
- Maps the exception to an HTTP status code.
- Converts exceptions into a standardized
ProblemDetailsorValidationProblemDetails. - Writes the response using
IProblemDetailsService.
Configurator
Contains extension methods for:
- Registering services
- Configuring middleware
- Register services in
Program.cs
builder.Services.UseExceptionHandling();- Configure middleware in
Program.cs
app.UseExceptionHandling();{
"title": "An error occured while validating your request",
"detail": "Invalid data",
"type": "ValidationException",
"status": 400,
"instance": "POST /api/users",
"extensions": {
"requestId": "00-abcd1234...",
"activityId": "00-xyz5678..."
}
}