通过Fsharp探索Enterprise Library Exception

Exception怎么生成是一回事,怎么展示又是还有一回事了。

Exception Block主要关注的点在于Exception信息的展示。Exception不同于一般的log信息,是系统设计者未考虑的错误情况。当异常出现时,错误的情况,或者暴露一些比較敏感的系统信息。或者将一些不怎么友好的信息显示给一些不怎么友好的客户。这时一个计算机异常就引入了一个客户异常,一个终极异常。所以异常处理的目标就是截断异常,进而恢复系统。

把合理的异常信息显示给相相应的用户。

因此主要的异常处理脉络也出现了。1.识别异常类型 2.决定处理策略 3.异常转化。第二点不是必须的,实际我们能够什么都不做。我们看一个最主要的样例

let exceptionShielding = [new ExceptionPolicyEntry(typeof<Exception>,
                                                        PostHandlingAction.ThrowNewException,
                                                        [|new WrapHandler("Application Error. Please contact rigid", typeof<Exception>)|])]

这个ExceptionPolicyEntry类的构造函数就包括了以上三个基本点。第一个參数是须要识别的异常类。实际的应用中异常特化的越具有特征性我们也就越可以识别此异常。只使用Exception带字符串对分类处理并没有什么优点。第二个枚举类型代表了处理策略。在处理完毕后再次抛出异常和忽略此异常都是比較经常使用的情况。最后是提供异常转化的详细方法,这里我们看到的是一个WrapHandler,类似于装饰者模式给原始的异常加一层壳。

详细的应用例如以下。

let policies = [new ExceptionPolicyDefinition("Wrap Exception", exceptionShielding)]

let exceptionManager = new ExceptionManager(policies)
ExceptionPolicy.SetExceptionManager(exceptionManager)

//most simple example
exceptionManager.Process((fun () -> 1/0 ), "Wrap Exception")

获取异常时我们不再使用try catch块,而是通过ExceptionManager的Process进行隐式处理。由于全部该进行的处理都在事先确定了,所以并不缺少什么。这里也并不是没有灵活处理异常的手段,也能够手动获得异常对象有针对性的进行处理。

我们做一个带日志的异常处理的样例。将原异常的信息进行替换后存入日志文件。

再进行封装操作。

首先应用日志模块生成一个日志处理对象

#if COMPILED
#else
#r "[Xpath]/packages/EnterpriseLibrary.Data.6.0.1304.0/lib/NET45/Microsoft.Practices.EnterpriseLibrary.Data.dll"
#r "[Xpath]/packages/EnterpriseLibrary.Common.6.0.1304.0/lib/NET45/Microsoft.Practices.EnterpriseLibrary.Common.dll"
#r "[Xpath]/packages/EnterpriseLibrary.ExceptionHandling.6.0.1304.0/lib/NET45/Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.dll"
#r "[Xpath]/packages/EnterpriseLibrary.ExceptionHandling.Logging.6.0.1304.0/lib/NET45/Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.dll"
#r "[Xpath]/packages/EnterpriseLibrary.Logging.6.0.1304.0/lib/NET45/Microsoft.Practices.EnterpriseLibrary.Logging.dll"
#r "System"
#r "System.Data"
#r "System.Configuration"
#r "System.ServiceModel"
#endif

open System
open System.Configuration
open Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
open Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging
open Microsoft.Practices.EnterpriseLibrary.Logging
open Microsoft.Practices.EnterpriseLibrary.Logging.Formatters
open Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners
open System.Diagnostics

//make logger
//format
let formatter = new TextFormatter("TimeStamp: {timestamp}{newline}Message:{message}{newline}Category:{category}{newline}Priority:{priority}{newline}EventID:{eventid}{newline}Severity:{severity}{newline}Title:{title}{newline}Machine:{machine}{newline}App Domain:{localAppDomain}{newline}ProcessID:{localProcessId}{newline}Process Name:{localProcessName}{newline}Thread Name:{threadName}{newline}Win32 ThreadID:{win32Thread}{newline}Extended Properties:{dictinary({key}-{value}{newline})}")
//listener
let flatFileTraceListener = new FlatFileTraceListener(@"c:\Temp\this.log", "------------------------------", "------------------------------",formatter)
let eventlog = new EventLog("Application", ".", "Enterprise Libray Logging")
let eventlogTraceListener = new FormattedEventLogTraceListener(eventlog)
//configuration
let config = new LoggingConfiguration()
config.AddLogSource("General", SourceLevels.All, true, [|flatFileTraceListener :> TraceListener|]) |> ignore
let logWriter = new LogWriter(config)

兴许的代码和之前的并无太大差别,加Policy条目。引用时注意类型字符串。

let exceptionShielding = [new ExceptionPolicyEntry(typeof<Exception>,
                                                        PostHandlingAction.ThrowNewException,
                                                        [|new WrapHandler("Application Error. Please contact rigid", typeof<Exception>)|])
                         ]

let replacingException = [new ExceptionPolicyEntry(typeof<Exception>,
                                                        PostHandlingAction.ThrowNewException,
                                                        [|new ReplaceHandler("Application Error. Please contact rigid", typeof<Exception>)|])
                         ]
let loggingAndReplacing = [new ExceptionPolicyEntry(typeof<Exception>,
                                                        PostHandlingAction.NotifyRethrow,
                                                        [|new LoggingExceptionHandler("General", 1000, TraceEventType.Error, "Rigid Service", 5, typeof<TextExceptionFormatter>, logWriter);
                                                          new ReplaceHandler("Application Error. Please contact rigid", typeof<Exception>)|])
                         ]

let policies = [new ExceptionPolicyDefinition("Wrap Exception", exceptionShielding);
                new ExceptionPolicyDefinition("Replace Exception", replacingException);
                new ExceptionPolicyDefinition("Log and Replace Exception", loggingAndReplacing)]

let exceptionManager = new ExceptionManager(policies)
ExceptionPolicy.SetExceptionManager(exceptionManager)

//most simple example
exceptionManager.Process((fun () -> 1/0 ), "Log and Replace Exception")

以上最基本概念,技术重点在异常怎样分类组织。与权限进行相应。

时间: 2024-08-16 10:34:29

通过Fsharp探索Enterprise Library Exception的相关文章

通过fsharp探索Enterprise Library DataBase 1.2

上一次讲到Enterprise Library中Data Access 模块的配置以及简单SQL语句和存储过程的执行.在探索的过程中应用Fsharp语言和交互环境能够马上看到结果,这感觉真的是非常通透. 1.提高数据库操作的复杂性,加入参数的变化,这一点和ADO的操作没有太多的不同. SQL语句带参数 let sqlStatement = "select top 1 * from OrderList where State like @state" using(defaultDB.Ge

通过fsharp探索Enterprise Library 6 DataBase 1.3 Sqlite

使用Enterprise Library就是为了尽可能少的开发常用组件.数据库在选择的过程中常会面临部署,版权,个人喜好等诸多考量.最佳的处理方法就是添加一层数据抽象层,再切换Enterprise的过程中进行无缝衔接.由于我的笔记本跑的越来越慢,又想尝试一下使用Sqlite所以,就用Sqlite做例子. 我用的是Enterprise Library 6.0原本以为只需要简单的配置就可以进行实验,没想到GitHub上Sqlite提供的Sqlite兼容组件到Enterprise Library 4.

通过fsharp 使用Enterprise Library Unity 3 - 三种拦截模式的探索

这篇就三种拦截模式进行一下探索. 特性总结   类型 特点 其它 InterfaceInterceptor Innstance 仅单接口 类内部函数互相引用无法引起拦截行为 TransparentProxyInterceptor           Instance 多接口(接口之间能够切换)  MarshalByRef 执行缓慢 接口类型(virtual, non-virtual, or interface) 类内部函数互相引用能够引起拦截行为 VirtualMethodInterceptor

通过fsharp 使用Enterprise Library Unity

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">使用Ioc概念的Unity库的优点,简单的说就是进一步解耦系统各组件的依赖关系.客户端代码只需依赖需要使用的接口(服务)就可以快速的进行开发.</span> 1.基本流程,定义类-->配置container-->解析类,并使用-->析构(依策略) 2.注册的

通过fsharp 使用Enterprise Library Unity 4 - Policy Interjection

policy interception Interception class拦截器还可以用Policy 以一种更高效的方式进行加载使用.拦截和被拦截对象的关系常见的是一对多,因为被拦截的主要是对象的方法所以有时数量巨大.Policy具有定义匹配模式的功能,所以可以简化这一匹配工作,不用一一添加被拦截对象.匹配的模式有 ? Assembly name ? Namespace ? Type ? Tag attribute ? Custom attribute ? Member name ? Meth

通过fsharp 使用Enterprise Library Unity 2

接着Depandency Injection继续. 最想做的还是用现成的程序模块对程序进行行为注入.只是不急,在此之前自己写一个接口对象观察一下IInterceptionBehavior接口的功效. type LogingInterceptionBehavior() = let WriteLog message = printfn "From the logging interceptor: %A" message interface IInterceptionBehavior wit

Microsoft Enterprise Library 6.0 之 Exception 企业库异常处理

对于企业库异常处理,这里做个简单的介绍和笔记. 环境 VS2012, .NET Framework 4.0, Microsoft Enterprise Library 6.0 准备工作 1. 下载Enterprise Library配置编辑工具:Microsoft.Practices.EnterpriseLibrary.ConfigConsoleV6.vsix. 下载地址:http://www.microsoft.com/en-us/download/details.aspx?id=38789

Enterprise Library 5.0 系列教程

1. Microsoft Enterprise Library 5.0 系列教程(一) Caching Application Block (初级) 2. Microsoft Enterprise Library 5.0 系列教程(一) Caching Application Block (高级) 3. Microsoft Enterprise Library 5.0 系列教程(二) Cryptography Application Block (初级) 4. Microsoft Enterpr

Enterprise Library 6.0 Semantic Logging Application Block Configuration

使用Enterprise Library 6.0的Logging application 模块,配置步骤如下: 1.Nuget 安装 Enterprise Library Logging模块 命令行:Install-package EnterpriseLibrary.Logging. 2.配置文件: 当前基本都是通过Enterprise Library 配置的,但是很不幸,我的总是安装失败,于是自己baidu了一把,然后进行配置,配置如下: <configSections> <secti