添加引用:
获取Facade类
ExceptionManager ExManager = EnterpriseLibraryContainer.Current.GetInstance ();
EnterpriseLibraryContainer位于Microsoft.Practices.EnterpriseLibrary.Common.Configuration;需要using下.
错误处理样板代码:
//==================
try{
.....你的操作,可能会抛出错误
}catch(Exception ex){
if (ExManager.HandleException(ex, "错误处理策略名称")) throw;
}
//===============
"错误处理策略名称",指你在错误处理模块配置指定的名称。
也可以使用 return ExceptionManager.Process(()=>MyMethod(18,"sss",...)) 进行调用
下面是Process的实现代码,跟上面的样板代码一样
代码 /// /// Executes the supplied delegate , and handles /// any thrown exception according to the rules configured for . /// /// Type of return value from . /// The delegate to execute. /// The value to return if an exception is thrown and the /// exception policy swallows it instead of rethrowing. /// The name of the policy to handle. /// If no exception occurs, returns the result from executing . If /// an exception occurs and the policy does not re-throw, returns . public override TResult Process < TResult > (Func < TResult > action, TResult defaultResult, string policyName) { if (action == null ) throw new ArgumentNullException( " action " ); if (policyName == null ) throw new ArgumentNullException( " policyName " ); try { return action(); } catch (Exception e) { if (HandleException(e, policyName)) { throw ; } } return defaultResult; }如果你电脑上有多个Ent Lib相关程序集(Release,Src,Hands On labs)请注意程序集的引用,默认情况下强类型程序集(PublicKeyToken!=null)是不允许引用未签名的程序集的,下面是可能的错误提示。
//===============引用错误===============
创建 exceptionHandling 的配置节处理程序时出错: 未能加载文件或程序集“Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35”或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配。 (异常来自 HRESULT:0x80131040)
//=================
为避免这个问题请在程序中引用跟配置工具(EntLibConfig.exe)同目录的程序集
参考下图可知道,一个Policy,会捕获一组错误,而每个错误,多允许配置多个处理者(Handler)
这个处理者的动作包括替换,包装,记录等处理。
每个错误类型可以设置Post Handling action, 分别取None,NotifyRethrow,thorwNewExcetpion等三个枚举
指定的错误被捕获,HandleException会根据配置逐一执行Handle,接着就根据Post Handling action设置进行相应处理
这个设置需要配合上面的样板代码来实现功能,列举如下:
None:HandleException返回false,不会执行throw;故错误将就此“消失”
NotifyRethrow:HandleException返回true,throw将被执行,原始错误被抛出。
throwNewExcetpion:HandleException返回true,throw将被执行,但是错误类型被替换成Wrap Handler或ReplaceHandler指定的类型,错误抛出点(Stack trace)将会出现在Handle内部(企业库),当然Wrap Handler会将原始错误封装在innerException中。
注意throw;跟throw ex;是不同的 throw ex将会将原始错误发生点改成当前throw ex的位置。