We can make use of the built-in UseExceptionHandler() middleware for catching Global Errors in ASP.NET Core.
app.UseExceptionHandler(err =>
{
err.Run(async ctx =>
{
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
// gets error detail
var ex = context.Features.Get<IExceptionHandlerPathFeature>();
var error = new MyResponseModel() { Content = ex.Error.Message };
await context.Response.WriteAsync(JsonConvert.SerializeObject(error));
});
});