Handling Exceptions Globally in ASP.NET Core
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
var exception = exceptionHandlerPathFeature?.Error;
await context.Response.WriteAsync("An error occurred.");
});
});