Updated Oct 22 2021 :: by Alex Yumashev

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

'ASP.NET Core global exception handling: Error page and a lambda' was written by Alex Yumashev
Alex Yumashev
Alex has founded Jitbit in 2005 and is a software engineer passionate about customer support.


Subscribe comments Tweet