.netcore2.1 封装全局打印异常信息过滤器

 

  • 设置异常信息拦截
复制代码
 public class GlobalExceptionFilter : IExceptionFilter
    {
        readonly ILogger _logger;

        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            _logger.LogError(context.Exception, context.Exception.Message);
            if (context.Exception is ShowMessageException)
            {
                context.Result = new JsonResult(context.Exception.Message);
            }
            else
            {
              
                context.Result = new JsonResult("服务器异常");
            }


            context.ExceptionHandled = true;
        }
    }
复制代码
  • 定义异常类
   public class ShowMessageException : Exception
    {
        public ShowMessageException(string message) : base(message)
        { }
    }
  •  在Startup.cs文件中,注入服务
复制代码
   public void ConfigureServices(IServiceCollection services)
        {

            //filters
            services.AddScoped<GlobalExceptionFilter>();



        }
复制代码

 

posted @ 2021-11-10 09:49  BK小鬼  阅读(75)  评论(0编辑  收藏  举报