Skip to content

UseHttpErrorResponses ​

Completes the standardized error handling, running the exception handlers registered through AddExceptionHandling and its siblings.

Two things are added, in order: the exception handler middleware that runs the registered handler chain, and a status code pages handler that fills in a body for any error response that has a status code but no content.

The second is what turns a bare return NotFound(); into a full error body without the endpoint doing anything, whether MVC produced the response or something below MVC did.

Usage ​

csharp
using AlmightyShogun.AspNet.Core;

WebApplication app = builder.Build();

app.UseHttpErrorResponses();
csharp
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("orders")]
public sealed class OrdersController : ControllerBase
{
    [HttpGet("{id:int}")]
    public IActionResult Get(int id) => NotFound();
}

The empty NotFound() above returns:

json
{
    "code": 404,
    "error": "not_found",
    "errorDescription": "The requested resource was not found."
}

TIP

errorDescription is resolved from the http-error.{status} message key in the language the caller negotiated. A status with no entry in that language falls back to the key itself, so the client sees http-error.404, and a 500 whose description cannot be resolved at all falls back the same way.

Pipeline order ​

Call it early, before routing and before endpoints, so it wraps the rest of the pipeline. An exception thrown by middleware registered before this call is not handled by it.

csharp
using AlmightyShogun.AspNet.Core;

WebApplication app = builder.Build();

app.UseForwardedHeaders();
app.UseMessageLocalization();
app.UseHttpErrorResponses();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Returns

The same IApplicationBuilder instance with HTTP error responses configured.

Type signature ​

csharp
public IApplicationBuilder UseHttpErrorResponses();

All packages are released under the MIT License.