這一篇記錄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});