exception filter

    public class MyExceptionFilter : IAsyncExceptionFilter
    {
        private IWebHostEnvironment WebHostEnvironment { get; set; }

        public MyExceptionFilter(IWebHostEnvironment webHostEnvironment)
        {
            WebHostEnvironment = webHostEnvironment;
        }

        Task IAsyncExceptionFilter.OnExceptionAsync(ExceptionContext context)
        {
            string message = string.Empty;

            if (WebHostEnvironment.IsDevelopment())
            {
                message = context.Exception.ToString();
            }
            else
            {
                message = "unhandled exception in server side";
            }

            ObjectResult result = new ObjectResult(new {code = 500, message = message });

            result.StatusCode = 500;
            context.Result = result;
            context.ExceptionHandled = true;

            return Task.CompletedTask;
        }
    }

注入

builder.Services.Configure<MvcOptions>(opt =>
{
    opt.Filters.Add<MyExceptionFilter>();
});