Netcore使用Filter来实现接口的全局异常拦截

 

public class MyException : Attribute, IExceptionFilter
    {
        private readonly ILogger<MyException> _logger;

        public MyException(ILogger<MyException> logger)
        {
            _logger = logger;
        }
        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                //写入日志
                _logger.LogError($"出错:{context.Exception.Message}");

                //定义返回信息
                var res = new
                {
                    Code = 500,
                    Message = "发生错误,请联系管理员"
                };
                context.Result = new ContentResult
                {
                    // 返回状态码设置为200,表示成功
                    StatusCode = StatusCodes.Status200OK,
                    // 设置返回格式
                    //ContentType = "application/json;charset=utf-8",
                    //Content = JsonConvert.SerializeObject(res)
                    ContentType = "text/html;charset=utf-8",
                    Content = $"<h2 style='color:red'>发生错误 :{context.Exception.Message}</h2>"
                };
                context.ExceptionHandled = true;
            }
        }
    }
  services.AddControllersWithViews(options=>
            {
                options.Filters.Add(typeof(MyException));
            });

 

posted @ 2021-05-29 07:19  lunawzh  阅读(237)  评论(0编辑  收藏  举报