2/10/2023 9:44:36 PM

The following can be added to your Startup.cs file as a global exception handler. From here, you can grab the exception and do...whatever you want with it. I wrapped the exception logic in a try catch just to ensure we don't throw a new unhandled exception.

app.UseExceptionHandler(exceptionHandlerApp => { exceptionHandlerApp.Run(async context => { //being extra careful with the try catch to not throw exception in exception handler try { var ex = context.Features.Get<IExceptionHandlerFeature>(); if (ex != null && ex.Error != null) { //do someting with the error } } catch (Exception ex) { //don't do anything here but maybe add a breakpoint to understand if you enounter an additional error } //return a 500 response code context.Response.StatusCode = StatusCodes.Status500InternalServerError; //return plain text content context.Response.ContentType = Text.Plain; //return simple text response await context.Response.WriteAsync("An exception was thrown."); ////if you want to check for an error related to the request path //var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>(); //if (exceptionHandlerPathFeature?.Error is FileNotFoundException) //{ // await context.Response.WriteAsync(" The file was not found."); //} //if (exceptionHandlerPathFeature?.Path == "/") //{ // await context.Response.WriteAsync(" Page: Home."); //} }); });