HandleErrorAttribute过滤器的使用
MVC提供了处理异常的ExceptionFilter接口IExceptionFilter,当然也提供了默认的实现HandleErrorAttribute,一般来说不建议自定义区实现IExceptionFilter来处理异常,继承HandleErrorAttribute就行了。
ASP.NET MVC 默认提供了一个异常过滤器HandleError特性,使用该特性可以极为方便的捕捉并处理控制器和操作抛出的异常,也可以将此特性注册为全局异常过滤器从而捕捉项目中的所有异常。
使用此过滤器需要在web.config中进行配置后方可使用,在system.web中进行配置,增加customerErrors节点
<customErrors mode="On" defaultRedirect="~/Error/Index"></customErrors>
对于错误代码如404,403等HandleErrorAttribute不会进行处理,需要通过配置来实现,所以在customerErrors节点中增加此配置
<error statusCode="404" redirect="~/Error/Errornotfoundpage"/>
<error statusCode="400" redirect="~/Error/Errornotfoundpage"/>
新建ErrorControl控制器
public class ErrorController : Controller
{
//
// GET: /Error/
public ActionResult Index()
{
return View();
}
public ActionResult Errornotfoundpage()
{
return View();
}
public ActionResult Errorpage()
{
return View();
}
}
Index为默认错误跳转地址,配置中defaultRedirect跳转所指向
Errornotfoundpage为404,403错误跳转页面,可以看到配置中就有写跳转到此地址,页面显示如
Errorpage为自定义过滤器跳转的地址,接下来我们将建立一个自定义的例外处理过滤器,通过继承HandleErrorAttribute来实现
重写OnException这个方法,在此我们可以获取控制器,action以及错误信息等,可以进行我们自定义处理,如写入日志等,当然可以跳转到指定的页面
public class CustomerErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
/* 调用基类的OnException方法,实现基础的功能。
* 如果要完全的自定义,就不需要调用基类的方法
*/
base.OnException(filterContext);
//可以放比如日志等功能
var controller = filterContext.RouteData.Values["controller"].ToString();
var action = filterContext.RouteData.Values["action"].ToString(); ;
errmsg model = new errmsg();
model.msg = filterContext.Exception.InnerException != null ? filterContext.Exception.InnerException.Message : filterContext.Exception.Message;
filterContext.Result = new ViewResult()
{
ViewName = "~/Views/Error/Errorpage.cshtml",
ViewData = new ViewDataDictionary<errmsg>(model),
TempData = filterContext.Controller.TempData
};
}
}
我们可以这里我们在models建立一个类来传递页面中的数据,让页面上显示当前出错的信息。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MVCStudy.Models
{
public class errmsg
{
public string msg { get; set; }
}
}
页面代码如下
@model MVCStudy.Models.errmsg
<h2></h2>
错误代码为:@Model.msg
然后我们可以使用此过滤器,如果想特定使用某个控制器或action的话通过特性的方式加上就可以了
[CustomerError]
public ContentResult test()
{
int i, j;
i = 1; j = 0;
return Content((i / j).ToString());
}
我们运行此程序,显示的画面
当然如果要全局使用的话,打开项目下App_Start的FilterConfig类(全局过滤器配置类)
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
我个人认为基本上这样使用HandleErrorAttribute以能够帮我们处理大部分程序产生的异常了。