Controller级别的异常处理过滤器IExceptionFilter

时间:2022-03-24 04:11:03

1,系统自带的HandleErrorAttribute类继承自IExceptionFilter,是MVC的默认实现。

同时设置web.config

<system.web>
<customErrors mode="On"/>

</system.web>

//只需要简单的将改特性放到controller类头上,告诉MVC如果该Controller中的Action方法出现异常,都交由HandleError特性处理
[HandleError(ExceptionType = typeof(System.Data.DataException), View = "Error")]
public class HomeController : Controller{
/* Controller Actions with HandleError applied to them */
}

HandleErrorAttribute类中OnException方法的源代码如下:

// System.Web.Mvc.HandleErrorAttribute
public virtual void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (filterContext.IsChildAction)
{
return;
}
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
Exception exception = filterContext.Exception;
if (new HttpException(null, exception).GetHttpCode() != )
{
return;
}
if (!this.ExceptionType.IsInstanceOfType(exception))
{
return;
}
string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];
HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult
{
ViewName = this.View,
MasterName = this.Master,
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = ;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}

2,自定义方式

方式一:

可以重写自定义过滤器,重写HandleErrorAttribute类中的OnException方法

同样设置web.config

<system.web>
<customErrors mode="On"/>
</system.web>

public class MyHandleErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
//自定义
}
}

然后,把自定义过滤器“MyHandleError”放到Controller的头上即可,

[MyHandleError(ExceptionType = typeof(System.Data.DataException), View = "Error")]
public class HomeController : Controller{
/* Controller Actions with HandleError applied to them */
}

方式二:

System.Web.Mvc.Controller类,也继承自IExceptionFilter,但是没有实现OnException方法,因此可以在Controller下重写(实现)OnException方法

同样设置web.config

<system.web>
<customErrors mode="On"/>
</system.web>

public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext); // 当自定义显示错误 mode = On,显示友好错误页面
if (filterContext.HttpContext.IsCustomErrorEnabled)
{
filterContext.ExceptionHandled = true;
this.View("Error").ExecuteResult(this.ControllerContext);
}
}
}