ASP.NET MVC中的错误处理

ASP.NET MVC中的错误的错误处理跨越了两个主要领域:程序异常和路由异常的处理。前者是关于在控制器和视图中捕获错误的;而后者更多是有关重定向和HTTP错误的。

1、在WebConfig中把过滤器配置启动

    <customErrors mode="On">
    </customErrors>

控制器的代码报错时,会跳转到~/Views/Shared/Error.cshtml页面。mode="Off"页面不会跳转直接显示错误信息。

2、绑定异常过滤器(过滤范围是在controller的action方法中。)

    public class FilterConfig
    {
        //效果相当于每个控制器的方法都添加了这个特性
        //[HandleError(ExceptionType = typeof(NullReferenceException), View = "error")]
        //public ActionResult Index()
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }

3、处理路由异常

    <customErrors mode="On">
      <error statusCode="404" redirect="~/Home/Index"/>
    </customErrors>

4、使用HTTP模块的全局错误处理

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        protected void Application_Error(object sender,EventArgs e)
        {
            var exception = Server.GetLastError();
            if (exception == null)
                return;
            Server.ClearError();
        }
    }