MVC全局异常日志

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tx1721110240/article/details/81127802

由软谋eleven老师提供

/// <summary>
    /// 全局抓Exception与记录日志
    /// </summary>
    [AttributeUsage(AttributeTargets.Class,Inherited=true,AllowMultiple=false)]
    public class LogExceptionFilter:HandleErrorAttribute
    {
        private Logger logger = Logger.CreateLogger(typeof(LogExceptionFilter));
        public override void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                string controllerName = (string)filterContext.RouteData.Values["controller"];
                string actionName = (string)filterContext.RouteData.Values["action"];
                string msgTemplate = "在执行 controller[{0}] 的 action[{1}] 时产生异常";
                logger.Error(string.Format(msgTemplate, controllerName, actionName), filterContext.Exception);
                
                ///判断访问形势
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult()
                    {
                        Data = new AjaxResult()
                        {
                            Result = DoResult.Failed,
                            PromptMsg = "系统出现异常,请联系管理员",
                            DebugMessage = filterContext.Exception.Message
                        }
                    };
                }
                else 
                { 
                    filterContext.Result=new ViewResult()
                    {
                        ViewName = "~/Views/Shared/Error.cshtml",
                        ViewData = new ViewDataDictionary<string>(filterContext.Exception.Message)
                    };
                }
                filterContext.ExceptionHandled = true;

            }
        }
    }

设置全局详看:点击进入

展开阅读全文

没有更多推荐了,返回首页