MVC默认提供了一个异常过滤器 HandleErrorAttribte特性

这一篇记录MVC默认提供了一个异常过滤器 HandleErrorAttribte,下一篇介绍自定义异常过滤特性html

参考引用:https://www.cnblogs.com/TomXu/archive/2011/12/15/2285432.htmlweb

前言

一直在给Team的人强调“Good programming is good Error Handling”,没人喜欢YSOD(Yellow Screen of Death)。我每次看到黄页的时候都是心惊肉跳的,尤为是在给客户演示的时候,因此在任什么时候候,若是出现黄页是因为你开发的代码致使的话,对不起,我会给你的绩效打很低的分。

固然,有些状况的黄页,在某些特殊的状况,咱们可能真的没法预知,但咱们起码得一些技巧让终端用户看不到这个YSOD页面。code

方案

幸运的是,在MVC3里有现成的功能支持让咱们能够作到这一点,它就是HandleErrorAttribte类,有2种方式可使用它,一是在类或者方法上直接使用HandleError属性来定义:htm

// 在这里声明
[HandleError]
public class HomeController : Controller
{
// 或者在这里声明
// [HandleError]
public ActionResult Index()
{
return View();
}
}


另一种方式是使用MVC3的Global Filters功能来注册,默认新建MVC项目在Global.asax文件里就已经有了,代码以下:blog

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

}

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}


代码段里的filters.Add(new HandleErrorAttribute());设置是说整个程序全部的Controller都使用这个HandleErrorAttribute来处理错误。

注意:HandleErrorAttribute只处理500系列错误,因此404错误须要另外单独处理,稍后会提到。


下一步,咱们要作的是开启web.config根目录里的customErrors(不是views目录下的那个web.config哦),代码以下:开发

<customerrors mode="On" defaultredirect="~/Error/HttpError">
<error redirect="~/Error/NotFound" statuscode="404" />
</customerrors>

defaultredirect是设置为全部错误页面转向的错误页面地址,而里面的error元素能够单独定义不一样的错误页面转向地址,上面的error行就是定义404所对应的页面地址。

最后一件事,就是定义咱们所须要的错误页面的ErrorController:get

public class ErrorController : BaseController
{
//
// GET: /Error/
public ActionResult HttpError()
{
return View("Error");
}
public ActionResult NotFound()
{
return View();
}
public ActionResult Index()
{
return RedirectToAction("Index", "Home");
}
}


默认Error的view是/views/shared/Error.cshtml文件,咱们来改写一下这个view的代码,代码以下:qt

@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = "General Site Error";
}

<h2>A General Error Has Occurred</h2>

@if (Model != null)
{
<p>@Model.Exception.GetType().Name<br />
thrown in @Model.ControllerName @Model.ActionName</p>
<p>Error Details:</p>
<p>@Model.Exception.Message</p>
}


你也能够经过传递参数来重写GlobalFilter里的HandleErrorAttribte注册,单独声明一个特定的Exception,而且带有Order参数,固然也能够连续声明多个,这样就会屡次处理。it

filters.Add(new HandleErrorAttribute{    ExceptionType = typeof(YourExceptionHere),    // DbError.cshtml是一个Shared目录下的view.    View = "DbError",    Order = 2});
相关文章
相关标签/搜索