服务端增加WCF服务全局异常处理机制

服务端增加WCF服务全局异常处理机制,任一WCF服务或接口方式出现异常,将统一调用WCF_ExceptionHandler.ProvideFault方法,因此不需要每个方法使用try catch写法。

C# Code:

 1 /// <summary> 
 2 /// WCF服务端异常处理器 
 3 /// </summary> 
 4 public class WCF_ExceptionHandler : IErrorHandler
 5 {
 6    #region IErrorHandler Members
 7    
 8    /// <summary> 
 9    /// HandleError 
10    /// </summary> 
11    /// <param name="ex">ex</param> 
12    /// <returns>true</returns> 
13    public bool HandleError(Exception ex)
14    {
15       return true;
16    }
17    
18    /// <summary> 
19    /// ProvideFault 
20    /// </summary> 
21    /// <param name="ex">ex</param> 
22    /// <param name="version">version</param> 
23    /// <param name="msg">msg</param> 
24    public void ProvideFault(Exception ex, MessageVersion version, ref Message msg)
25    {
26       // 
27       //在这里处理服务端的消息,将消息写入服务端的日志 
28       // 
29       string err = string.Format("调用WCF接口 '{0}' 出错", ex.TargetSite.Name) ",详情:
" ex.Message;
30       var newEx = new FaultException(err);
31       
32       MessageFault msgFault = newEx.CreateMessageFault();
33       msg = Message.CreateMessage(version, msgFault, newEx.Action);
34    }
35    
36    #endregion
37 }
C# Code:

 1 /// <summary> 
 2 /// WCF服务类的特性 
 3 /// </summary> 
 4 public class WCF_ExceptionBehaviourAttribute : Attribute, IServiceBehavior
 5 {
 6    private readonly Type _errorHandlerType;
 7    
 8    public WCF_ExceptionBehaviourAttribute(Type errorHandlerType)
 9    {
10       _errorHandlerType = errorHandlerType;
11    }
12    
13    #region IServiceBehavior Members
14    
15    public void Validate(ServiceDescription description,
16    ServiceHostBase serviceHostBase)
17    {
18    }
19    
20    public void AddBindingParameters(ServiceDescription description,
21    ServiceHostBase serviceHostBase,
22    Collection<ServiceEndpoint> endpoints,
23    BindingParameterCollection parameters)
24    {
25    }
26    
27    public void ApplyDispatchBehavior(ServiceDescription description,
28    ServiceHostBase serviceHostBase)
29    {
30       var handler =
31       (IErrorHandler)Activator.CreateInstance(_errorHandlerType);
32       
33       foreach (ChannelDispatcherBase dispatcherBase in
34       serviceHostBase.ChannelDispatchers)
35       {
36          var channelDispatcher = dispatcherBase as ChannelDispatcher;
37          if (channelDispatcher != null)
38          channelDispatcher.ErrorHandlers.Add(handler);
39       }
40    }
41    
42    #endregion
43 }

使用:

C# Code:

1 [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
2 [WCF_ExceptionBehaviour(typeof(WCF_ExceptionHandler))]
3 public class AccountModuleService : IAccountModuleService
4 {
5    
6    //code
7 
8 }   

原文地址:https://www.cnblogs.com/yanglang/p/6963268.html