back to Jitbit Blog home About this blog

ASP.NET Core global exception handling: Error page and a lambda

by Alex Yumashev · Updated Oct 22 2021

One of the (many) annoyances we bumped into when rewriting Jitbit Helpdesk 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

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
    });
});

But what if you want ot do both - show an error page and use a lambda? Preferably without the bulky context.Features.Get<IExceptionHandlerPathFeature>? 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"
	}
});