ASP.NET MVC基于异常处理的解决方案

发表于:2012-1-13 09:55

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:Artech    来源:51Testing软件测试网采编

  三、通过配置的Error View处理异常

  在上面的配置中,针对InvalidUserNameException和UserNamePasswordNotMatchException这两种异常类型的配置策略都将PostHandlingAction属性设置为“None”,意味着不会将原来的异常和处理后的异常进行重新抛出。现在我们将该属性设置为“ThrowNewException”,意味着我们会将处理后的异常重新抛出来。

  1. <exceptionHandling> 
  2. <exceptionPolicies> 
  3. <addnameaddname="myPolicy"> 
  4. <exceptionTypes> 
  5. <addnameaddname="InvalidUserNameException"type="Artech.Mvc.ExceptionHandling.Models.InvalidUserNameException, Artech.Mvc.ExceptionHandling"  
  6. postHandlingAction="ThrowNewException"> 
  7. ...  
  8. <addnameaddname="UserNamePasswordNotMatchException"type="Artech.Mvc.ExceptionHandling.Models.UserNamePasswordNotMatchException, Artech.Mvc.ExceptionHandling"9:postHandlingAction="ThrowNewException"> 
  9. ...  
  10. </add> 
  11. </exceptionTypes> 
  12. </add> 
  13. </exceptionPolicies> 
  14. </exceptionHandling>

  按照我们上面的异常处理策略,在这种情况下我们将采用“错误页面”的方式来进行异常处理。也HandleErrorAttribute的处理方式类似,我们支持异常类型和Error View之间的匹配关系,而这是通过类似于如下的配置来定义的。值得一提的是,这里的异常类型是经过处理后重新抛出的异常

  1. <exceptionHandling> 
  2. <exceptionPolicies> 
  3. <addnameaddname="myPolicy"> 
  4. <exceptionTypes> 
  5. <addnameaddname="InvalidUserNameException"type="Artech.Mvc.ExceptionHandling.Models.InvalidUserNameException, Artech.Mvc.ExceptionHandling"  
  6. postHandlingAction="ThrowNewException"> 
  7. ...  
  8. <addnameaddname="UserNamePasswordNotMatchException"type="Artech.Mvc.ExceptionHandling.Models.UserNamePasswordNotMatchException, Artech.Mvc.ExceptionHandling"9:postHandlingAction="ThrowNewException"> 
  9. ...  
  10. </add> 
  11. </exceptionTypes> 
  12. </add> 
  13. </exceptionPolicies> 
  14. </exceptionHandling>

  如上面的配置所示,我们为InvalidUserNameException和UserNamePasswordNotMatchException这两种异常类型定义了不同的Error View,分别是“InvalideUserNameError”和“UserNamePasswordNotMatchError”,详细定义如下所示:

  1. @{  
  2. Layout = null;  
  3. }  
  4. <!DOCTYPEhtml> 
  5. <html> 
  6. <head> 
  7. <title>Error</title> 
  8. </head> 
  9. <body> 
  10. <pstylepstyle="color:Red; font-weight:bold">Sorry,the user name you specify does not exist!</p> 
  11. </body> 
  12. </html> 
  13.  @{  
  14. Layout = null;  
  15. }  
  16. <!DOCTYPEhtml> 
  17. <html> 
  18. <head> 
  19. <title>Error</title> 
  20. </head> 
  21. <body> 
  22. <pstylepstyle="color:Red; font-weight:bold">Sorry, The password does not match the given user name!</p> 
  23. </body> 
  24. </html>

53/5<12345>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号