DEV Community

Alex Yumashev
Alex Yumashev

Posted on • Originally published at jitbit.com

2 1

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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay