巧用ASP.net MVC3里的HandleErrorAttribute

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

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

方案

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

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


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

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:

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的代码,代码如下:

@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参数,当然也可以连续声明多个,这样就会多次处理。

filters.Add(new HandleErrorAttribute
{
    ExceptionType = typeof(YourExceptionHere),
    // DbError.cshtml是一个Shared目录下的view.
    View = "DbError",
    Order = 2
});

同步与结束语

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值