A lightweight library for throwing HTTP status code exceptions using clean, expressive static helper methods.
# Base library
dotnet add package HttpStatusExceptions
# ASP.NET Core integration (includes ProblemDetails support)
dotnet add package HttpStatusExceptions.AspNetCoreusingHttpStatusExceptions;// Using static throw helpersHttpStatusException.Throw404NotFound();HttpStatusException.Throw401Unauthorized("Invalid API key.");// Or throw directlythrownewHttpStatusException(404,"Resource not found.");Generic overloads let you throw in expression contexts—useful for null-coalescing and conditional expressions:
varitem=awaitdb.Items.FirstOrDefaultAsync(item =>item.Id==id)??HttpStatusException.Throw404NotFound<Item>("Item not found.");varresult=isValid?ProcessData():HttpStatusException.Throw400BadRequest<Result>();The HttpStatusExceptions.AspNetCore package adds a ToProblemDetails() extension method:
usingHttpStatusExceptions.AspNetCore;// In Program.csbuilder.Services.AddProblemDetails(options =>{options.CustomizeProblemDetails=(ctx)=>{ctx.ProblemDetails=MapProblemDetails(ctx.Exception);};});staticProblemDetailsMapProblemDetails(Exception?ex)=>exswitch{HttpStatusExceptionhttpEx=>httpEx.ToProblemDetails(),
_ =>newProblemDetails{Detail="An unexpected error occurred.",Status=StatusCodes.Status500InternalServerError,}};All standard 4xx and 5xx status codes are supported:
| Category | Status Codes |
|---|---|
| 4xx Client Errors | 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 421, 422, 423, 424, 426, 428, 429, 431, 451 |
| 5xx Server Errors | 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511 |
Additionally, 405 Method Not Allowed has method-specific helpers: Throw405GetNotAllowed(), Throw405PostNotAllowed(), Throw405PutNotAllowed(), Throw405DeleteNotAllowed(), etc.