Skip to content

Repository files navigation

HttpStatusExceptions

HttpStatusExceptionsHttpStatusExceptions.AspNetCoreLicense

A lightweight library for throwing HTTP status code exceptions using clean, expressive static helper methods.

Installation

# Base library
dotnet add package HttpStatusExceptions
# ASP.NET Core integration (includes ProblemDetails support)
dotnet add package HttpStatusExceptions.AspNetCore

Usage

Throwing Exceptions

usingHttpStatusExceptions;// Using static throw helpersHttpStatusException.Throw404NotFound();HttpStatusException.Throw401Unauthorized("Invalid API key.");// Or throw directlythrownewHttpStatusException(404,"Resource not found.");

Generic Variants

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>();

ProblemDetails Support (ASP.NET Core)

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,}};

Supported Status Codes

All standard 4xx and 5xx status codes are supported:

CategoryStatus Codes
4xx Client Errors400, 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 Errors500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511

Additionally, 405 Method Not Allowed has method-specific helpers: Throw405GetNotAllowed(), Throw405PostNotAllowed(), Throw405PutNotAllowed(), Throw405DeleteNotAllowed(), etc.

About

A lightweight library for throwing HTTP status code exceptions using clean, expressive static helper methods.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages