zoukankan      html  css  js  c++  java
  • ASP.NET MVC4 异常拦截

    ASP.NET MVC4 程序发生异常时,通过拦截Action的异常,重写ActionFilterAttribute 的方法OnActionExecuted实现。

    具体实现代码如下:

        /// <summary>
        /// 拦截Action的异常
        /// </summary>
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
        public class ExceFilterAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuted(ActionExecutedContext filterContext)
            {
                if (filterContext.Exception != null)
                {
                    object[] attrs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(LigerUIExceptionResultAttribute), true);
                    if (attrs.Length == 1)//判断是否属于LigerUIResult的Action
                    {
                        string msgTmp= "<b>异常消息:  </b>{0}</p><b>触发Action:  </b>{1}</p><b>异常类型:  </b>{2}";
                        var excResult = new JsonResult();
                        excResult.Data = AjaxResult.Error(string.Format(msgTmp,
                                    filterContext.Exception.GetBaseException().Message,
                                    filterContext.ActionDescriptor.ActionName,
                                    filterContext.Exception.GetBaseException().GetType().ToString()));
                        LogHelper.WriteLog("系统错误:" + excResult.Data);
                        filterContext.Result = excResult;
                    }
                    else
                    {
                        filterContext.Controller.ViewData["ErrorMessage"] = String.Format(@"<b>异常消息: {0}</br><b>触发Action:  </p>{1}</br><b>异常类型:  </b>{2}",
                            filterContext.Exception.GetBaseException().Message,
                            filterContext.ActionDescriptor.ActionName,
                            filterContext.Exception.GetBaseException().GetType().ToString());
                        LogHelper.WriteLog("系统错误:" + filterContext.Controller.ViewData["ErrorMessage"].ToString ());
                        filterContext.Result = new ViewResult()
                       {
                           ViewName = "Error",
                           ViewData = filterContext.Controller.ViewData,
                       };
    
                    }
                    filterContext.ExceptionHandled = true;
                }
            }
        }
  • 相关阅读:
    当期所得税费用总额
    所得税净利润算法
    [AGC028B]Removing Blocks 概率与期望
    bzoj 4319: cerc2008 Suffix reconstruction 贪心
    bzoj 2430: [Poi2003]Chocolate 贪心
    BZOJ 2839: 集合计数 广义容斥
    luogu 5505 [JSOI2011]分特产 广义容斥
    CF504E Misha and LCP on Tree 后缀自动机+树链剖分+倍增
    CF798D Mike and distribution 贪心
    CF707D Persistent Bookcase 可持久化线段树
  • 原文地址:https://www.cnblogs.com/mikechang/p/3273120.html
Copyright © 2011-2022 走看看