question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Mapping Exception x StatusCode in ExceptionHandlerMiddleware

See original GitHub issue

Background and Motivation

In .NET 7 the ExceptionHandlerMiddleware was updated to generate a Problem Details when the IProblemDetailsService is registered.

While this change allows a consistent ProblemDetails for the application the default handler for ExceptionHandlerMiddleware always sets the response status code to 500 and changing to produce a different Status Code requires a custom implementation (as mentioned here #43831).

Proposed API

The community ProblemDetails middleware (https://github.com/khellang/Middleware) has a capability to map an Exception to Status Code when producing the payload. Since the ExceptionHandlerMiddleware is the built-in feature to handle exception, my suggestion is to add a similar feature to allow mapping exception type X status code every time an exception is handled.

namespace Microsoft.AspNetCore.Builder;

public class ExceptionHandlerOptions
{
+    public void Map<TException>(int statusCode) where TException : Exception {}
+    public bool TryGetMap(Exception exception, out int statusCode) {}
}

Usage Examples

Configuring the ExceptionHandlerOptions

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddExceptionHandler(o => 
{
    o.Map<InvalidOperationException>(400);
});

var app = builder.Build();

app.UseExceptionHandler();

app.MapGet("/", () =>
{
    throw new InvalidOperationException();
});

app.Run();

Setting ExceptionHandlerOptions directly to the middleware

var app = WebApplication.Create(args);

var options = new ExceptionHandlerOptions();
options.Map<InvalidOperationException>(400);

app.UseExceptionHandler(options);

app.MapGet("/", () =>
{
    throw new InvalidOperationException();
});

app.Run();

Alternative Designs

Alternative names

public void AddMap<TException>(int statusCode) where TException : Exception {} public void MapStatusCode<TException>(int statusCode) where TException : Exception {} public void MapToStatusCode<TException>(int statusCode) where TException : Exception {}

Using a property instead

namespace Microsoft.AspNetCore.Builder;

public class ExceptionHandlerOptions
{
+    public IDictionary<Type, int> StatusCodeMapping { get; } = new Dictionary<Type, int>();
}

The disadvantage of this design is the Dictionary potentially accepts any type, not necessarily an Exception type.

cc @khellang

Issue Analytics

  • State:open
  • Created a year ago
  • Reactions:9
  • Comments:11 (10 by maintainers)

github_iconTop GitHub Comments

2reactions
davidfowlcommented, Sep 24, 2022

I like the dictionary because it gives the ability to manipulate the data (CRUD). IMO Map isn’t a clear name, I like MapStatusCode

1reaction
mitchdennycommented, Apr 18, 2023

I don’t anyone is working on it yet @brunolins16 - it’s all yours 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

ASP.NET Core Web API exception handling
So when exception is not caught anywhere, exception handling middleware catches it and re-runs the pipeline for a route, registered in it. This ......
Read more >
Handle errors in ASP.NET Core web APIs
This article describes how to handle errors and customize error handling with ... Exception { public HttpResponseException(int statusCode, ...
Read more >
Creating a custom ErrorHandlerMiddleware function
In this post I show how to customise the ExceptionHandlerMiddleware to create custom responses when an error occurs in your middleware ...
Read more >
ASP.NET Core global exception handling gotchas
Implementing an ASP.NET global exception handler is usually done for purposes such as: Translating exception types into HTTP status codes, ...
Read more >
Handling errors in ASP.NET Core Web API - DevTrends
This post looks at the best ways to handle exceptions, validation and other invalid requests such as 404s in ASP.NET Core Web API...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found