Exception Handling引入MVP

时间:2023-12-01 17:39:20

异常处理(Exception Handling)是所有系统的最基本的基础操作之一,其它的比如日志(Logging)、审核(Auditing)、缓存(Caching)、事务处理(Transaction)等;

今天,来把异常处理引入到我们在《MVP之V和P的交互》中Calculator的实例中,简单的实现AOP。实例运行如图:

Exception Handling引入MVP

那么,开始我们开简单的介绍下Enterprise Library EHAB(Exception Handling Application Block)提供了一种基于策略(Policy)的异常处理方式。具体的可以参考这里

如何配置

具体的配置如下:

<configuration>
<configSections>
<section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
   <exceptionHandling>
<exceptionPolicies>
<add name="UIExceptionPolicy">
<exceptionTypes>
<add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="None">
<exceptionHandlers>
<add type="Handwe.Demo.UnityInMVP.MessageBoxHandler, Handwe.Demo.UnityInMVP"
name="Custome Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>

这些是可以通过配置工具来配置的;现在我们来说说具体的内容:

<exceptionPolicies>
<add name="UIExceptionPolicy">

添加一个名为UIExceptionPolicy的异常策略;

 <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="None">

配置要处理的异常类型,这里是所有异常;postHandlingAction="None"是无后续处理;

 <exceptionHandlers>
<add type="Handwe.Demo.UnityInMVP.MessageBoxHandler, Handwe.Demo.UnityInMVP"
name="Custome Handler" />

exceptionHandlers添加的是一个我们自定义的处理程序,名为MessageBoxHandler,就是简单的一个弹出式消息框;

代码的实现

  • 引用程序集

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;

  • 异常处理程序MessageBoxHandler
 namespace Handwe.Demo.UnityInMVP
{
[ConfigurationElementType(typeof(CustomHandlerData))]
public class MessageBoxHandler : IExceptionHandler
{
public MessageBoxHandler(NameValueCollection igonre)
{ }
public Exception HandleException(Exception exception, Guid handlingInstanceId)
{
MessageBox.Show(exception.Message, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return exception;
}
}
}

这里很简单也没有用到相应的参数配置;

try
{
this.OnCalculating(op1, op2);
}
catch (Exception ex)
{
if (ExceptionPolicy.HandleException(ex, "UIExceptionPolicy"))
{
throw;
}
}

修改并应用以上代码;指定异常处理策略;

小结

通过Entlib的EHAB,我们可以专注于具体的业务逻辑上,类似异常之类的非业务处理可以通过后期的配置来实现。