服務端增長WCF服務全局異常處理機制

轉自:http://www.csframework.com/archive/1/arc-1-20150109-2193.htm框架

服務端增長WCF服務全局異常處理機制,任一WCF服務或接口方式出現異常,將統一調用WCF_ExceptionHandler.ProvideFault方法,所以不須要每一個方法使用try catch寫法。ide

 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) ",詳情:\r\n" 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 }
38 
39 //來源:C/S框架網(www.csframework.com) QQ:1980854898
 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 }
44 
45 //來源:C/S框架網(www.csframework.com) QQ:1980854898

使用:spa

1 [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
2 [WCF_ExceptionBehaviour(typeof(WCF_ExceptionHandler))]
3 public class AccountModuleService : IAccountModuleService
4 {
5    
6    //來源:C/S框架網(www.csframework.com) QQ:1980854898
7 
8 
9 }   
相關文章
相關標籤/搜索