我想使用企业库异常处理块来进行异常处理。 为了尝试它,我编写了一个简单的应用程序,它抛出并处理异常,在玩它时我遇到了以下内容:
当我使用像System.ApplicationException
这样的BCL异常时,抛出的异常会被包装起来:
策略:
<exceptionPolicies>
<add name="DalPolicy">
<exceptionTypes>
<add name="DbPrimitiveHandledException" type="Exceptions.DbPrimitiveHandledException, Exceptions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add name="DAL Wrap Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WrapHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
exceptionMessage="Dal Wrapper Exception" wrapExceptionType="System.ApplicationException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
...
</exceptionPolicies>
控制台输出:
System.ApplicationException:Dal Wrapper Exception ---&gt; Exceptions.DbPrimitiveHandledException:Db Handled Policed exception ...
但是当我尝试使用自己的例外时:
public class DalWrapperException : Exception
{
public DalWrapperException()
{ }
public DalWrapperException(string message)
: base(message)
{ }
}
策略:
<exceptionPolicies>
<add name="DalPolicy">
<exceptionTypes>
<add name="DbPrimitiveHandledException" type="Exceptions.DbPrimitiveHandledException, Exceptions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add name="DAL Wrap Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WrapHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
exceptionMessage="Dal Wrapper Exception" wrapExceptionType="Exceptions.DalWrapperException, Exceptions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
...
</exceptionPolicies>
包装不起作用 - 我收到ExceptionHandlingException:
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionHandlingException: Unable to handle exception: 'WrapHandler'.
有人可以告诉我我的异常或配置有什么问题吗? 提前致谢
答案 0 :(得分:3)
问题在于异常类。它必须实现一个接受内部异常的构造函数:
public class DalWrapperException : Exception
{
public DalWrapperException()
{ }
public DalWrapperException(string message)
: base(message)
{ }
public DalWrapperException(string message, Exception innerException)
: base(message, innerException)
{ }
}