当前位置:Gxlcms > asp.net > ASP.NET MVC异常处理模块详解

ASP.NET MVC异常处理模块详解

时间:2021-07-01 10:21:17 帮助过:16人阅读

一、前言

  异常处理是每个系统必不可少的一个重要部分,它可以让我们的程序在发生错误时友好地提示、记录错误信息,更重要的是不破坏正常的数据和影响系统运行。异常处理应该是一个横切点,所谓横切点就是各个部分都会使用到它,无论是分层中的哪一个层,还是具体的哪个业务逻辑模块,所关注的都是一样的。所以,横切关注点我们会统一在一个地方进行处理。无论是MVC还是WebForm都提供了这样实现,让我们可以集中处理异常。

  在MVC中,在FilterConfig中,已经默认帮我们注册了一个HandleErrorAttribute,这是一个过滤器,它继承了FilterAttribute类和实现了IExceptionFilter接口。说到异常处理,马上就会联想到500错误页面、记录日志等,HandleErrorAttribute可以轻松的定制错误页,默认就是Error页面;而记录日志我们也只需要继承它,并替换它注册到GlobalFilterCollection即可。关于HandleErrorAttribute很多人都知道怎么使用了,这里就不做介绍了。

  ok,开始进入主题!在MVC中处理异常,相信开始很多人都是继承HandleErrorAttribute,然后重写OnException方法,加入自己的逻辑,例如将异常信息写入日志文件等。当然,这并没有任何不妥,但良好的设计应该是场景驱动的,是动态和可配置的。例如,在场景一种,我们希望ExceptionA显示错误页面A,而在场景二中,我们希望它显示的是错误页面B,这里的场景可能是跨项目了,也可能是在同一个系统的不同模块。另外,异常也可能是分级别的,例如ExceptionA发生时,我们只需要简单的恢复状态,程序可以继续运行,ExceptionB发生时,我们希望将它记录到文件或者系统日志,而ExceptionC发生时,是个较严重的错误,我们希望程序发生邮件或者短信通知。简单地说,不同的场景有不同的需求,而我们的程序需要更好的面对变化。当然,继承HandleErrorAttribute也完全可以实现上面所说的,只不过这里我不打算去扩展它,而是重新编写一个模块,并且可以与原有的HandleErrorAttribute共同使用。

二、设计及实现

2.1 定义配置信息

  从上面已经可以知道我们要做的事了,针对不同的异常,我们希望可以配置它的处理程序,错误页等。如下一个配置:

  1. <!--自定义异常配置-->
  2. <settingException>
  3. <exceptions>
  4. <!--add优先级高于group-->
  5. <add exception="Exceptions.PasswordErrorException"
  6. view ="PasswordErrorView"
  7. handler="ExceptionHandlers.PasswordErrorExceptionHandler"/>
  8. <groups>
  9. <!--group可以配置一种异常的view和handler-->
  10. <group view="EmptyErrorView" handler="ExceptionHandlers.EmptyExceptionHandler">
  11. <add exception="Exceptions.UserNameEmptyException"/>
  12. <add exception="Exceptions.EmailEmptyException"/>
  13. </group>
  14. </groups>
  15. </exceptions>
  16. </settingException>

  其中,add 节点用于增加具体的异常,它的 exception 属性是必须的,而view表示错误页,handler表示具体处理程序,如果view和handler都没有,异常将交给默认的HandleErrorAttribute处理。而group节点用于分组,例如上面的UserNameEmptyException和EmailEmptyException对应同一个处理程序和视图。

  程序会反射读取这个配置信息,并创建相应的对象。我们把这个配置文件放到Web.config中,保证它可以随时改随时生效。

2.2 异常信息包装对象

  这里我们定义一个实体对象,对应上面的节点。如下:

  1. public class ExceptionConfig
  2. {
  3. /// <summary>
  4. /// 视图
  5. /// </summary>
  6. public string View{get;set;}
  7. /// <summary>
  8. /// 异常对象
  9. /// </summary>
  10. public Exception Exception{get;set;}
  11. /// <summary>
  12. /// 异常处理程序
  13. /// </summary>
  14. public IExceptionHandler Handler{get;set;}
  15. }

2.3 定义Handler接口

  上面我们说到,不同异常可能需要不同处理方式。这里我们设计一个接口如下:

  1. public interface IExceptionHandler
  2. {
  3. /// <summary>
  4. /// 异常是否处理完成
  5. /// </summary>
  6. bool HasHandled{get;set;}
  7. /// <summary>
  8. /// 处理异常
  9. /// </summary>
  10. /// <param name="ex"></param>
  11. void Handle(Exception ex);
  12. }

  各种异常处理程序只要实现该接口即可。

2.3 实现IExceptionFilter

  这是必须的。如下,实现IExceptionFilter接口,SettingExceptionProvider会根据异常对象类型从配置信息(缓存)获取包装对象。

  1. public class SettingHandleErrorFilter : IExceptionFilter
  2. {
  3. public void OnException(ExceptionContext filterContext)
  4. {
  5. if(filterContext == null)
  6. {
  7. throw new ArgumentNullException("filterContext");
  8. }
  9. ExceptionConfig config = SettingExceptionProvider.Container[filterContext.Exception.GetType()];
  10. if(config == null)
  11. {
  12. return;
  13. }
  14. if(config.Handler != null)
  15. {
  16. //执行Handle方法
  17. config.Handler.Handle(filterContext.Exception);
  18. if (config.Handler.HasHandled)
  19. {
  20. //异常已处理,不需要后续操作
  21. filterContext.ExceptionHandled = true;
  22. return;
  23. }
  24. }
  25. //否则,如果有定制页面,则显示
  26. if(!string.IsNullOrEmpty(config.View))
  27. {
  28. //这里还可以扩展成实现IView的视图
  29. ViewResult view = new ViewResult();
  30. view.ViewName = config.View;
  31. filterContext.Result = view;
  32. filterContext.ExceptionHandled = true;
  33. return;
  34. }
  35. //否则将异常继续传递
  36. }
  37. }

2.4 读取配置文件,创建异常信息包装对象

  这部分代码比较多,事实上,你只要知道它是在读取web.config的自定义配置节点即可。SettingExceptionProvider用于提供容器对象。

  1. public class SettingExceptionProvider
  2. {
  3. public static Dictionary<Type, ExceptionConfig> Container =
  4. new Dictionary<Type, ExceptionConfig>();
  5. static SettingExceptionProvider()
  6. {
  7. InitContainer();
  8. }
  9. //读取配置信息,初始化容器
  10. private static void InitContainer()
  11. {
  12. var section = WebConfigurationManager.GetSection("settingException") as SettingExceptionSection;
  13. if(section == null)
  14. {
  15. return;
  16. }
  17. InitFromGroups(section.Exceptions.Groups);
  18. InitFromAddCollection(section.Exceptions.AddCollection);
  19. }
  20. private static void InitFromGroups(GroupCollection groups)
  21. {
  22. foreach (var group in groups.Cast<GroupElement>())
  23. {
  24. ExceptionConfig config = new ExceptionConfig();
  25. config.View = group.View;
  26. config.Handler = CreateHandler(group.Handler);
  27. foreach(var item in group.AddCollection.Cast<AddElement>())
  28. {
  29. Exception ex = CreateException(item.Exception);
  30. config.Exception = ex;
  31. Container[ex.GetType()] = config;
  32. }
  33. }
  34. }
  35. private static void InitFromAddCollection(AddCollection collection)
  36. {
  37. foreach(var item in collection.Cast<AddElement>())
  38. {
  39. ExceptionConfig config = new ExceptionConfig();
  40. config.View = item.View;
  41. config.Handler = CreateHandler(item.Handler);
  42. config.Exception = CreateException(item.Exception);
  43. Container[config.Exception.GetType()] = config;
  44. }
  45. }
  46. //根据完全限定名创建IExceptionHandler对象
  47. private static IExceptionHandler CreateHandler(string fullName)
  48. {
  49. if(string.IsNullOrEmpty(fullName))
  50. {
  51. return null;
  52. }
  53. Type type = Type.GetType(fullName);
  54. return Activator.CreateInstance(type) as IExceptionHandler;
  55. }
  56. //根据完全限定名创建Exception对象
  57. private static Exception CreateException(string fullName)
  58. {
  59. if(string.IsNullOrEmpty(fullName))
  60. {
  61. return null;
  62. }
  63. Type type = Type.GetType(fullName);
  64. return Activator.CreateInstance(type) as Exception;
  65. }
  66. }

  以下是各个配置节点的信息:

  settingExceptions节点:

  1. /// <summary>
  2. /// settingExceptions节点
  3. /// </summary>
  4. public class SettingExceptionSection : ConfigurationSection
  5. {
  6. [ConfigurationProperty("exceptions",IsRequired=true)]
  7. public ExceptionsElement Exceptions
  8. {
  9. get
  10. {
  11. return (ExceptionsElement)base["exceptions"];
  12. }
  13. }
  14. }

  exceptions节点:

  1. /// <summary>
  2. /// exceptions节点
  3. /// </summary>
  4. public class ExceptionsElement : ConfigurationElement
  5. {
  6. private static readonly ConfigurationProperty _addProperty =
  7. new ConfigurationProperty("", typeof(AddCollection), null, ConfigurationPropertyOptions.IsDefaultCollection);
  8. [ConfigurationProperty("", IsDefaultCollection = true)]
  9. public AddCollection AddCollection
  10. {
  11. get
  12. {
  13. return (AddCollection)base[_addProperty];
  14. }
  15. }
  16. [ConfigurationProperty("groups")]
  17. public GroupCollection Groups
  18. {
  19. get
  20. {
  21. return (GroupCollection)base["groups"];
  22. }
  23. }
  24. }

  Group节点集:

  1. /// <summary>
  2. /// group节点集
  3. /// </summary>
  4. [ConfigurationCollection(typeof(GroupElement),AddItemName="group")]
  5. public class GroupCollection : ConfigurationElementCollection
  6. {
  7. /*override*/
  8. protected override ConfigurationElement CreateNewElement()
  9. {
  10. return new GroupElement();
  11. }
  12. protected override object GetElementKey(ConfigurationElement element)
  13. {
  14. return element;
  15. }
  16. }

  group节点:

  1. /// <summary>
  2. /// group节点
  3. /// </summary>
  4. public class GroupElement : ConfigurationElement
  5. {
  6. private static readonly ConfigurationProperty _addProperty =
  7. new ConfigurationProperty("", typeof(AddCollection), null, ConfigurationPropertyOptions.IsDefaultCollection);
  8. [ConfigurationProperty("view")]
  9. public string View
  10. {
  11. get
  12. {
  13. return base["view"].ToString();
  14. }
  15. }
  16. [ConfigurationProperty("handler")]
  17. public string Handler
  18. {
  19. get
  20. {
  21. return base["handler"].ToString();
  22. }
  23. }
  24. [ConfigurationProperty("", IsDefaultCollection = true)]
  25. public AddCollection AddCollection
  26. {
  27. get
  28. {
  29. return (AddCollection)base[_addProperty];
  30. }
  31. }
  32. }

  add节点集:

  1. /// <summary>
  2. /// add节点集
  3. /// </summary>
  4. public class AddCollection : ConfigurationElementCollection
  5. {
  6. /*override*/
  7. protected override ConfigurationElement CreateNewElement()
  8. {
  9. return new AddElement();
  10. }
  11. protected override object GetElementKey(ConfigurationElement element)
  12. {
  13. return element;
  14. }
  15. }

  add节点:

  1. /// <summary>
  2. /// add节点
  3. /// </summary>
  4. public class AddElement : ConfigurationElement
  5. {
  6. [ConfigurationProperty("view")]
  7. public string View
  8. {
  9. get
  10. {
  11. return base["view"] as string;
  12. }
  13. }
  14. [ConfigurationProperty("handler")]
  15. public string Handler
  16. {
  17. get
  18. {
  19. return base["handler"] as string;
  20. }
  21. }
  22. [ConfigurationProperty("exception", IsRequired = true)]
  23. public string Exception
  24. {
  25. get
  26. {
  27. return base["exception"] as string;
  28. }
  29. }
  30. }

三、测试

  ok,下面测试一下,首先要在FilterConfig的RegisterGlobalFilters方法中在,HandlerErrorAttribute前注册我们的过滤器:

  filters.Add(new SettingHandleErrorFilter())。

3.1 准备异常对象

   准备几个简单的异常对象:

  1. public class PasswordErrorException : Exception{}
  2. public class UserNameEmptyException : Exception{}
  3. public class EmailEmptyException : Exception{}

3.2 准备Handler

  针对上面的异常,我们准备两个Handler,一个处理密码错误异常,一个处理空异常。这里没有实际处理代码,具体怎么处理,应该结合具体业务了。如:

  1. public class PasswordErrorExceptionHandler : IExceptionHandler
  2. {
  3. public bool HasHandled{get;set;}
  4. public void Handle(Exception ex)
  5. {
  6. //具体处理逻辑...
  7. }
  8. }
  9. public class EmptyExceptionHandler : IExceptionHandler
  10. {
  11. public bool HasHandled { get; set; }
  12. public void Handle(Exception ex)
  13. {
  14. //具体处理逻辑...
  15. }
  16. }

3.3 抛出异常

  按照上面的配置,我们在Action中手动throw异常

  1. public ActionResult Index()
  2. {
  3. throw new PasswordErrorException();
  4. }
  5. public ActionResult Index2()
  6. {
  7. throw new UserNameEmptyException();
  8. }
  9. public ActionResult Index3()
  10. {
  11. throw new EmailEmptyException();
  12. }

  可以看到,相应的Handler会被执行,浏览器也会出现我们配置的错误页面。

四、总结

  事实上这只是一个比较简单的例子,所以我称它为简单的模块,而是用框架、库之类的词。当然我们可以根据实际情况对它进行扩展和优化。微软企业库视乎也集成这样的模块,有兴趣的朋友可以了解一下。

人气教程排行