DEV Community

Alex Yumashev
Alex Yumashev

Posted on • Originally published at jitbit.com

Global exception handling in ASP.NET Core

One of the (many) annoyances we bumped into when rewriting our (huge) app from .NET Framework to .NET Core was the inability to handle exceptions globally both via an error page and some exception handling code.

See, .NET 5 has app.UseExceptionHandler() and the way you use it is either via error page (and extracting the actual error object on that page):

app.UseExceptionHandler("/Error"); //error handling page
Enter fullscreen mode Exit fullscreen mode

OR use the exception handling lambda:

app.UseExceptionHandler(errorApp => //error handling lambda
{
    errorApp.Run(async context =>
    {
        var exceptionHandlerPathFeature =
            context.Features.Get<IExceptionHandlerPathFeature>;();

        var exception = exceptionHandlerPathFeature?.Error;

        //do something with the exception
    });
});
Enter fullscreen mode Exit fullscreen mode

But what if you want to do both - show an error page and use a lambda to process the exception (for example, to send an error email)? Preferably without the bulky context.Features.Get<ExceptionHandlerPathFeature>? This is how:

app.UseExceptionHandler("/Error");
app.Use(async (context, next) => //add middleware
{
    try
    {
        await next.Invoke(); //run next middleware code
    }
    catch (Exception ex)
    {
        //do something
        throw; //re-throw so it's caught by the upper "/Error"
    }
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)