- usingSystem;
- usingSystem.Web.Mvc;
- namespaceArtech.Mvc.ExceptionHandling
- {
- publicabstractclassBaseController : Controller
- {
- publicBaseController(stringexceptionPolicy)
- {
- Func<string, HandleErrorInfo, ViewResult> getErrorView = (viewName, handleErrorInfo) => this.View(viewName, handleErrorInfo);
- this.ExceptionActionInvoker = newExceptionActionInvoker(exceptionPolicy,getErrorView);
- }
- publicBaseController(ExceptionActionInvoker actionInvoker)
- {
- this.ExceptionActionInvoker = actionInvoker;
- }
- publicvirtualExceptionActionInvoker ExceptionActionInvoker { get; privateset; }
- protectedvirtualstringGetHandleErrorActionName(stringactionName)
- {
- returnstring.Format("On{0}Error", actionName);
- }
- protectedoverridevoidOnException(ExceptionContext filterContext)
- {
- using(ExceptionHandlingContextScope contextScope = newExceptionHandlingContextScope(filterContext))
- {
- stringactionName = RouteData.GetRequiredString("action");
- stringhandleErrorActionName = this.GetHandleErrorActionName(actionName);
- this.ExceptionActionInvoker.InvokeAction(filterContext, handleErrorActionName);
- foreach(var error inExceptionHandlingContext.Current.Errors)
- {
- ModelState.AddModelError(Guid.NewGuid().ToString() ,error.ErrorMessage);
- }
- }
- }
- }
- }
值得一提的是:整个OnException方法中的操作都在一个ExceptionHandlingContextScope中进行的。顾名思义, 我们通过ExceptionHandlingContextScope为ExceptionHandlingContext创建了一个范围。ExceptionHandlingContext定义如下,我们可以通过它获得当前的ExceptionContext和ModelErrorCollection,而静态属性Current返回当前的ExceptionHandlingContext对象。
- publicclassExceptionHandlingContext
- {
- [ThreadStatic]
- privatestaticExceptionHandlingContext current;
- publicExceptionContext ExceptionContext { get; privateset; }
- publicModelErrorCollection Errors { get; privateset; }
- publicExceptionHandlingContext(ExceptionContext exceptionContext)
- {
- this.ExceptionContext = exceptionContext;
- this.Errors = newModelErrorCollection();
- }
- publicstaticExceptionHandlingContext Current
- {
- get { returncurrent; }
- set { current = value;}
- }
- }
在BaseController的OnException方法中,当执行了ExceptionActionInvoker的InvokeAction之后,我们会将当前ExceptionHandlingContext的ModelError转移到当前的ModelState中。这就是为什么我们会通过ValidationSummary显示错误信息的原