Can I write a custom exception handler for Kestrel?

21 Views Asked by At

I have an ASP.NET Core web service, reduced to the essentials:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

var app = WebApplication.Create();
app.Urls.Add("http://localhost:3001");
app.MapGet("/error", ThrowAnError);

string ThrowAnError()
{
    throw new SomeCustomException();
}

app.Run();

When I run this and browse to the /error end-point, I get a 500 response back. What I'd like to happen is for something to catch this specific exception and for my code to provide an alternative response instead. Is there please a way to pass in a custom error handler?

(The errors are things like 409-Conflict. I found it makes things a lot simpler if I throw an exception from deep in my code in this unusual event instead of engineering a tuple return with either a success or a rejection response at every layer.)

Side bar: at the moment, I'm passing a wrapper into MapGet that implements the try/catch and returns my custom response. (See my other recent question for the essentials.) The problem with this approach is that I end up bypassing a lot of what makes Kestrel so useful including JSON serializing response objects. I feel there must be a correct way to catch errors that isn't fighting against the system's architecture.

1

There are 1 best solutions below

2
Yehor Androsov On

Usually, you would use app.Use as a middleware to handle such cases

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", _ => throw new Exception("test"));

app.Use(async (context, next) =>
{
    try
    {
        await next(context);
    }
    catch 
    {
        context.Response.StatusCode = 409;
    }
});

app.Run();