ASP.NET2.0:AdventureWorks贸易系统
使用异常处理块
通过浏览www.microsoft.com/downloads和查找EntLib,开发人员可下载EntLib缓存块,其中包括了异常处理块。在安装完企业库之后,就可利用异常处理块开始编写代码。为正确使用异常处理块,需要遵循以下步骤:
1. 在解决方案中分别添加对Microsoft.Practices.EnterpriseLibrary.Common.dll和Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll程序集的引用,为此,可使用“添加引用”选项,并定位到<驱动程序名>:\Program Files\Microsoft Enterprise Library January 2006\bin文件夹。如果还需要结合异常处理使用日志记录,则再添加对Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll的引用。
2. 在app.config或者Web.config文件中添加必要的配置项。为此,可在根<configuration>元素下的<configSections>元素中添加如下内容:
<section name="exceptionHandling"3. 如果随同异常处理一起使用日志记录,则还需要在<configSections>元素中添加以下设置:
type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.
Configuration.ExceptionHandlingSettings,Microsoft.Practices.
EnterpriseLibrary.ExceptionHandling" />
<section name="loggingConfiguration"4. 接下来,直接在<configuration>元素下添加<exceptionHandling>元素。在<exceptionHandling>内部可添加所有的异常处理策略。以下代码说明在<exceptionHandling>中指定了一个名为“Global Policy”的策略。
type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.
LoggingSettings,Microsoft.Practices.EnterpriseLibrary.Logging" />
<exceptionHandling>5. 正如这些设置所指示的那样,有一个名为Log Only Policy的策略,该策略能够记录异常。使用<exceptionHandlers>节能够设置以适当方式处理异常的自定义异常处理程序。在这种情况下,自定义处理程序实现LoggingExceptionHandler类。postHandlingAction属性用于根据策略设置异常处理之后的行为。该属性包括以下可能值:None,NotifyRethrow和ThrowNewException。
<exceptionPolicies>
<add name="Log Only Policy">
<exceptionTypes>
<add name="Exception" type="System.Exception, mscorlib,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add logCategory="Default Category" eventId="100" severity="Error"
title="Exception Management Application Exception" priority="0"
formatterType="Microsoft.Practices.EnterpriseLibrary.
ExceptionHandling.TextExceptionFormatter,
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling"
name="Logging Handler"
type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.
Logging.LoggingExceptionHandler,
Microsoft.Practices.EnterpriseLibrary.
ExceptionHandling.Logging"/>
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
6. 在代码中导入异常处理块的核心命名空间Microsoft.Practices.EnterpriseLibrary.ExceptionHandling。
7. 开始使用上述命名空间中的类编写代码。
0
相关文章