Useful WCF Behaviors - IErrorHandler
Behaviors in WCF are so stinking useful, and once you get past the basics of WCF they're arguably a necessity. Microsoft has saved itself from hundreds of hours of cursing by including the ability to define custom behaviors.
My favorite use of behaviors is addressing some cross cutting concerns that we consistently have in our WCF services. Specifically logging, service registration, wsdl tweaking, and error handling. Which brings us around to the IErrorHandler interface.
Implementing IErrorHandler "Allows an implementer to control the fault message returned to the caller and optionally perform custom error processing such as logging". Thank you MSDN. IErrorHandler has two methods to implement: HandleError, and ProvideFault. Implement them so that they do what they say they do. HandleError should do something with the error (in our case, we log it) and ProvideFault should return a fault message.
#region IErrorHandler Members
// HandleError. Log an error, then allow the error to be handled as usual.
// Return true if the error is considered as already handled
public bool HandleError(Exception error)
{
try
{
\\our loggin service
LoggerClient logger = new LoggerClient(basic, logAddress);
\\build log message
StringBuilder err = new StringBuilder();
err.AppendLine("Source: " + error.Source);
err.AppendLine("Target: " + error.TargetSite.ToString());
err.AppendLine("Message: " + error.Message);
err.AppendLine("Stack Trace: " + error.StackTrace.ToString());
CustomLogEntry log = new CustomLogEntry();
log.AppDomainName = AppDomain.CurrentDomain.FriendlyName;
log.EventId = 900;
log.EventIdSpecified = true;
log.MachineName = Environment.MachineName;
log.Message = err.ToString();
log.Priority = 1;
log.PrioritySpecified = true;
log.Severity = TraceEventType.Error;
log.SeveritySpecified = true;
log.Title = "Exception Caught: " + error.Message;
logger.Log(log);
return true;
}
catch (Exception)
{
throw new Exception("error in the handler");
}
}
public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
{
// Shield the unknown exception
FaultException faultException = new FaultException(error.Message);
MessageFault messageFault = faultException.CreateMessageFault();
fault = Message.CreateMessage(version, messageFault, faultException.Action);
}
#endregion
Pretty straight forward.
Now we just have to figure out a way to get this to apply to our service, preferably without a lot of extra work. So we don't want to go mucking around with attributes or anything else we have to remember to stick in as we're writing the code. That's where behaviors come in. You can apply them via the config file.
We know we want this particular behavior to apply to our entire service, so we want to implement IServiceBehavior in our class along with IErrorHandler. IServiceBehavior has four methods that we have to implement, but fortunately we can ignore three of them. The one we care about in this case is ApplyDispatchBehavior, where we will apply our error handler to each of the channels in the service. In the example below ErrorHandler is the name of the class we are implementing. Inventive name, isn't it?
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
IErrorHandler errorHandler = new ErrorHandler();
foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
{
ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;
channelDispatcher.ErrorHandlers.Add(errorHandler);
}
}
Great, that's done. Now there's only one thing left to do. We need a class that inherits from BehaviorExtensionElement so that we can add our behavior via configuration. Fortunately BehaviorExtensionElement is a breeze to implement. You need to impelement BehaviorType which just returns the type of your just implement IServiceBehavior class (ErrorHandler above), and CreateBehavior which returns an instantiation of the class.
class ErrorHandlerBehavior : BehaviorExtensionElement
{
public override Type BehaviorType
{
get
{
return typeof(ErrorHandler);
}
} protected override object CreateBehavior()
{
return new ErrorHandler();
}
}
Now the code is done. The last thing to do is to apply the newly created behavior in the config file. Add our new BehaviorExtensionElement to the behaviorExtensions section, and then specify it in the serviceBehaviors section. One important caveat, if includeExceptionDetailInFaults is set to true, then the exception shielding (and I believe Error Handling) will not work.
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="ErrorLogging" type="ErrorHandlerBehavior, ErrorHandling, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8746502a48718374" />
</behaviorExtensions>
</extensions>
<bindings>
<basicHttpBinding>
<binding name="basicBinding">
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="Service1Behavior" name="Service">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicBinding" contract="Service" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Service1Behavior">
<serviceMetadata httpGetUrl="" httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
<ErrorLogging />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
There you go. Apply this to all of your WCF services and you won't have to re-invent the wheel again.
Useful WCF Behaviors - IErrorHandler的更多相关文章
- Wcf实现IServiceBehavior拓展机制
IServiceBehavior接口 描述:提供一种在整个服务内修改或插入自定义拓展机制: 命名空间: System.ServiceModel.Description程序集: System.Ser ...
- BizTalk 开发系列(四十) BizTalk WCF-SQL Adapter读取SQL Service Broker消息
SQL Service Broker 是在SQL Server 2005中新增的功能.Service Broker 为 SQL Server 提供队列和可靠的消息传递,可以可用来建立以异步消息为基础的 ...
- 在web.config里使用configSource分隔各类配置
转:http://www.yongfa365.com/Item/using-configSource-Split-Configs.html 大型项目中,可能有多个Service,也就是会有一堆配置,而 ...
- 【WCF】自定义错误处理(IErrorHandler接口的用法)
当被调用的服务操作发生异常时,可以直接把异常的原始内容传回给客户端.在WCF中,服务器传回客户端的异常,通常会使用 FaultException,该异常由这么几个东东组成: 1.Action:在服务调 ...
- WCF扩展系列 - 行为扩展(Behaviors)
原文地址:http://www.cnblogs.com/Creator/archive/2011/05/21/2052687.html 这个系列的第一部分将会重点关注WCF行为(behaviors), ...
- 【WCF】错误处理(四):一刀切——IErrorHandler
前面几篇烂文中所介绍到的错误方式,都是在操作协定的实现代码中抛出 FaultException 或者带泛型参数的detail方案,有些时候,错误的处理方法比较相似,可是要每个操作协定去处理,似乎也太麻 ...
- 利用Attribute和IErrorHandler处理WCF全局异常
在处理WCF异常的时候,有大概几种方式: 第一种是在配置文件中,将includeExceptionDetailInFaults设置为true <behavior name="servi ...
- 【转】WCF扩展系列 - 行为扩展(Behaviors)
原文:https://www.cnblogs.com/Creator/archive/2011/05/21/2052687.html 这个系列的第一部分将会重点关注WCF行为(behaviors),W ...
- WCF入门(22)
前言 本还想写一集WCF入门教程的,心情实在不好,明天又还有面试,改天再写吧. 说一下今天遇到的入职坑.面试能坑,上班能坑,完全没想到入职也能坑.切身经历. 今年10月份想换工作,更新了一下简历,接到 ...
随机推荐
- U盘拷贝大文件提示文件过大无法拷贝解决方案
工具: 计算机 windows操作系统 U盘 原因:由于U盘的格式问题导致的,当期的磁盘格式是FAT32类型的,无拷贝过大的文件 方法:接下来修改U盘类型,且不格式化U盘 1.键盘win+R快捷键弹出 ...
- 高版本sonar安装遇到的坑-sonar 6.7.5
最近安装了6.7.5版本的sonar,发现里面的坑还是很多,下面列举下遇到的坑 sonar插件地址:https://docs.sonarqube.org/display/PLUG/Plugin+Lib ...
- JS及Dom示例 | 分级菜单折叠
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- SC OpenService 失败5:拒绝访问
当我们在cmd里使用 sc delete 服务名 ,来删除服务的时候,报错误,SC OpenService 失败5:拒绝访问. 这似乎是因为权限不够,解决方法. 首先,我们必须先取得管理员权限,以 ...
- Jmeter断言实例—响应断言
断言有很多种,最最最常用的一种就是响应断言,目前我用的最多是这一种,下面列举一个运用响应断言的实例 对相应的请求添加断言 **Main sample and sub-samples:断言应用于主采样器 ...
- selenium中等待元素的加载
在实际使用中,有时会出现一个元素还没有加载出来,导致无法获取,此时需要selenium处理来等待一段时间,此时处理方法有以下几种: 1.最笨.最简单但是最不推荐的方式: Thread.sleep(ti ...
- jquery colsest的用法
如果有class,就是他自己,没有就在父级去找 e=e||window.event; var target=e.srcElement?e.srcElement:e.target; var parent ...
- Visual Studio中修改项目的输出目录
1. 如在Solution中的项目名称为 ProjectA 但在本地目录显示却想换成: MyProject 2. 应该做的修改是: 2.1. 将本地目录的 ProjectA手动修改成 MyProjec ...
- bat执行java程序 good
start.bat set MY_HOME=%~dp0 set JMS_BINDING_PATH=%MY_HOME%..\binds set JAVA_HOME=C:\Program Files\J ...
- jquery 使用整理机制
短路表达式 与 多重短路表达式 短路表达式这个应该人所皆知了.在 jQuery 中,大量的使用了短路表达式与多重短路表达式. 短路表达式:作为"&&"和" ...