.NET MVC5专题(特性篇【异常处理】HandleError)

用户异常特性

[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())//检查请求头 是不是XMLHttpRequest
            {
                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;
        }
    }
}

控制器和方法使用直接在前面加上[LogException]全局使用如下

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            //filters.Add(new HandleErrorAttribute());
            filters.Add(new CustomHandleErrorAttribute());//全部的控制器全部的action都生效
        }

捕获异常情况表

//1 Action异常,没被catch T
//2 Action异常,被catch F
//3 Action调用Service异常 T 异常冒泡
//4 Action正常视图出现异常 T ExecuteResult是包裹在try里面的
//5 控制器构造出现异常 F 控制器构造后才有Filter
//6 Action名称错误 F 因为请求其实都没进mvc流程
//7 任意错误地址 F
//8 权限Filter异常 T 权限fileter也是在try里面的

需要异常全部捕获还需要在全局文件添加

/// <summary>
/// 全局式的异常处理,可以抓住漏网之鱼
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Application_Error(object sender, EventArgs e)
{
    Exception excetion = Server.GetLastError();
    this.logger.Error($"{base.Context.Request.Url.AbsoluteUri}出现异常");
    Response.Write("System is Error....");
    Server.ClearError();

    //Response.Redirect
    //base.Context.RewritePath("/Home/Error?msg=")
}
发布了153 篇原创文章 · 获赞 123 · 访问量 7239

猜你喜欢

转载自blog.csdn.net/weixin_41181778/article/details/103960051