how to do error handing with WCF by using attributes to log your errors z

There are multiple ways to do error handling in WCF as listed by Pedram Rezaei Blog.
The default way that WCF allows errors
message to display is by setting IncludeExceptionDetailInFaults Property to true in web.config or on the service attribute but this is only recommended when you need to debug you development code not in your shipped/release code.
In Web.config file
In the web.config file of the WCF service the includeExceptionDetailFaults attribute set it to true. With this action every endpoint associated to WCF service will send managed exception information.
<services>
<service name="ZeytinSoft.WCF.OliveService"
behaviorConfiguration="OliveDebugServiceConfiguration">
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="OliveDebugServiceConfiguration">
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
 | 
 <system.serviceModel> 
    <services> 
        <service name="ZeytinSoft.WCF.OliveService" 
                         behaviorConfiguration="OliveDebugServiceConfiguration"> 
        </service> 
    </services> 
    <behaviors> 
        <serviceBehaviors> 
            <behavior name="OliveDebugServiceConfiguration"> 
                <serviceDebug includeExceptionDetailInFaults="true"/> 
            </behavior> 
        </serviceBehaviors> 
    </behaviors> 
</system.serviceModel> 
 | 
In Attribute
Another way is setting the IncludeExceptionDatailInFaults property to true using the ServiceBehaviorAttribute.
public class OliveService{ }
| 
 1 
2 
 | 
 [ServiceBehavior(IncludeExceptionDetailInFaults=true)] 
public class OliveService{ } 
 | 
That is fine and dandy but it is definitely not recommended for production server, you don’t want an stack trace to show up when someone is viewing it on the webpage for this service.
The IErrorHandler interface
The basic form of error logging in WCF is to use the IErrorHandler interface, which enables developers to customize the default exception reporting and propagation, and provides for a hook for custom logging.
{
bool HandleError(Exception error);
void ProvideFault(Exception error,MessageVersion version,ref Message fault);
}
| 
 1 
2 
3 
4 
5 
 | 
 public interface IErrorHandler 
{ 
   bool HandleError(Exception error); 
   void ProvideFault(Exception error,MessageVersion version,ref Message fault); 
} 
 | 
Another thing to note is we need to implement the IServiceBehavior also since installing our own custom implementation of IErrorHandler requires adding it to the desired dispatcher. Since we need to treat the extensions as custom service behaviors in order for it to work.
{
void AddBindingParameters(ServiceDescription description,
ServiceHostBase host,
Collection <ServiceEndpoint> endpoints,
BindingParameterCollection parameters);
void ApplyDispatchBehavior(ServiceDescription description,
                              ServiceHostBase host);
void Validate(ServiceDescription description,ServiceHostBase host);
}
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
 | 
 public interface IServiceBehavior 
{ 
   void AddBindingParameters(ServiceDescription description, 
                             ServiceHostBase host, 
                             Collection <ServiceEndpoint> endpoints, 
                             BindingParameterCollection parameters); 
   void ApplyDispatchBehavior(ServiceDescription description, 
                              ServiceHostBase host); 
   void Validate(ServiceDescription description,ServiceHostBase host); 
} 
 | 
Rather than just calling Log4Net I create a class called Logger which decouples log4net so that one can use any logging framework by using a dependency injection framework. (Code not listed)
Back to building our own ErrorHandler, ServiceBehavior with Attribute, the code is listed below
public class OliveErrorHandlerBehaviorAttribute : Attribute, IServiceBehavior, IErrorHandler
{
protected Type ServiceType { get; set; }
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
//Dont do anything
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection <ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
		{
			//dont do anything
		}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
		{
			ServiceType = serviceDescription.ServiceType;
			foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
			{
				dispatcher.ErrorHandlers.Add(this);
			}
		}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
		{
			fault = null; //Suppress any faults in contract
		}
public bool HandleError(Exception error)
		{
			Logger.LogException(error); //Calls log4net under the cover
			return false;
		}
}
| 
 1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
 | 
 [AttributeUsage(AttributeTargets.Class)] 
public class OliveErrorHandlerBehaviorAttribute : Attribute, IServiceBehavior, IErrorHandler 
{ 
 protected Type ServiceType { get; set; } 
 public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
 { 
 //Dont do anything 
 } 
 public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection <ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters) 
 { 
 //dont do anything 
 } 
 public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
 { 
 ServiceType = serviceDescription.ServiceType; 
 foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers) 
 { 
 dispatcher.ErrorHandlers.Add(this); 
 } 
 } 
 public void ProvideFault(Exception error, MessageVersion version, ref Message fault) 
 { 
 fault = null; //Suppress any faults in contract 
 } 
 public bool HandleError(Exception error) 
 { 
 Logger.LogException(error); //Calls log4net under the cover 
 return false; 
 } 
} 
 | 
Now one can just add an attribute to the WCF service code to log our error message to log4net or whatever logging framework that you may be using.
[OliveErrorHandlerBehavior]
public class OliveService{ }
| 
 1 
2 
3 
 | 
  [ServiceContract] 
 [OliveErrorHandlerBehavior] 
 public class OliveService{ } 
 | 
There is also another way by using the web.config and adding the error logging to all the services listed by Stever B in his blog, but I find that does not give me the flexibility that I wanted, I may want to log some but not others etc.
how to do error handing with WCF by using attributes to log your errors z的更多相关文章
- 使用WCF的Trace与Message Log功能
		
原创地址:http://www.cnblogs.com/jfzhu/p/4030008.html 转载请注明出处 前面介绍过如何创建一个WCF Service http://www.cnblo ...
 - mysqldump: Got error: 1556: You can't use locks with log tables. when using LOCK TABLES
		
mysqldump: Got error: 1556: You can't use locks with log tables. when using LOCK TABLES 我是把一些mysqldu ...
 - [mysql] ERROR 1862 (HY000): Your password has expired. To log in you must change it using a client that supports expired passwords.
		
今天安装mysql遇到这样一个问题: ERROR 1862 (HY000): Your password has expired. To log in you must change it using ...
 - 【故障处理】ERROR 1872 (HY000): Slave failed to initialize relay log info structure from the repository
		
今天在使用冷备份文件重做从库时遇到一个报错,值得研究一下. 版本:MySQL5.6.27 一.报错现象 dba:(none)> start slave; ERROR (HY000): Slave ...
 - 安装RabbitMQ编译erlang时,checking for c compiler default output file name... configure:error:C compiler cannot create executables See 'config.log' for more details.
		
checking for c compiler default output file name... configure:error:C compiler cannot create executa ...
 - postman Installation has failed: There was an error while installing the application. Check the setup log for more information and contact the author
		
Error msg: Installation has failed: There was an error while installing the application. Check the s ...
 - jmeter3.2生成图形html遇到的问题Error in NonGUIDriver java.lang.IllegalArgumentException: Results file:log is not empty
		
遇到Creating summariser <summary> Error in NonGUIDriver java.lang.IllegalArgumentException: Resu ...
 - (转)mysqldump: Got error: 1556: You can't use locks with log tables.
		
mysqldump: Got error: 1556: You can't use locks with log tables. 原文:http://blog.51cto.com/oldboy/112 ...
 - mysql 主从关系ERROR 1872 (HY000): Slave failed to initialize relay log info structure from the repository
		
连接 amoeba-mysql出现Could not create a validated object, cause: ValidateObject failed mysql> start s ...
 
随机推荐
- selenium 之Ran 0 tests in 0.000s
			
from selenium import webdriverfrom time import ctime,sleepimport unittestclass TestLogin(unittest.Te ...
 - 百度ECharts数据绑定诀窍
			
百度Echarts的功能还是蛮好用的.. 不能说多好但是也不次.. 下边就分享一些数据绑定经验..对在处理过程中的思路有一些帮助... 报表里用的最多的可以说是 饼状图和柱形图.. 饼状图里当然是包括 ...
 - ScriptManager.RegisterStartupScript失效的解决方案
			
在项目中一个页面使用System.Web.UI.ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "success ...
 - Apache和Tomcat的整合过程(转载)
			
一 Apache与Tomcat比较联系 apache支持静态页,tomcat支持动态的,比如servlet等. 一般使用apache+tomcat的话,apache只是作为一个转发,对jsp的处理是由 ...
 - KOA 与 CO 实现浅析
			
KOA 与 CO 的实现都非常的短小精悍,只需要花费很短的时间就可以将源代码通读一遍.以下是一些浅要的分析. 如何用 node 实现一个 web 服务器 既然 KOA 实现了 web 服务器,那我们就 ...
 - Django 入门项目案例开发(下)——创建项目应用及模型类
			
关注微信公众号:FocusBI 查看更多文章:加QQ群:808774277 获取学习资料和一起探讨问题. 前面两章是在已经开发好的项目上用来描述环境和业务,这一章创建一个全新的项目来用作开发,你可以跟 ...
 - linux-pm2用法
			
devo.ps团队对JavaScript的迷恋已经不是什么秘密了;node.js作为服务器端,AngularJS作为客户端,某种程度上说,我们的堆栈是用它建成的.我们构建静态客户端和RESTful J ...
 - 利用Map解决复杂业务
			
遍历出题库表的题库名称和题库id,根据题目id即questionBankId获取 分组,即该题库题目总数,该题库题目正确数,该题库已回答题目数. <sqltemplate id="co ...
 - JVM, JRE,JDK 的区别
			
在网上看到一篇讲解jvm,jre,jdk区别的文章,感觉不错,就收藏到自己的博客了. 1.JVM -- java virtual machine JVM就是我们常说的java虚拟机,它是整个java实 ...
 - jstl缺包时的报错
			
jsp中:<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 报错: ...