2013-07-31 55 views
7

我基本上实现了IErrorHandler接口,通过执行ProvideFault方法来捕获WCF服务中的各种异常并将其发送给客户端。使用IErrorHandler处理WCF异常

但是我面临一个关键问题。所有异常都以FaultException的形式发送给客户端,但这会禁用客户端来处理他可能已在服务中定义的特定异常。

考虑:SomeException已被定义并抛入其中一个OperationContract实现中。当异常被抛出,它使用下面的代码转换为故障:

var faultException = new FaultException(error.Message); 
MessageFault messageFault = faultException.CreateMessageFault(); 
fault = Message.CreateMessage(version, messageFault, faultException.Action); 

这并发送错误作为一个字符串,但客户已经赶上一般般例外:

try{...} 
catch(Exception e){...} 

而不是:

try{...} 
catch(SomeException e){...} 

不仅自定义异常喜欢SomeException,但系统异常喜欢InvalidOperationException异常,不能使用上述方法捕获。

有关如何实现此行为的任何想法?

回答

9

在WCF需要使用描述为合同特殊的例外,因为你的客户可能不具有有关标准.NET异常信息.NET应用程序。 为此,您可以在您的服务中定义FaultContract,然后使用FaultException类。

服务器端

[ServiceContract] 
public interface ISampleService 
{ 
    [OperationContract] 
    [FaultContractAttribute(typeof(MyFaultMessage))] 
    string SampleMethod(string msg); 
} 

[DataContract] 
public class MyFaultMessage 
{ 
    public MyFaultMessage(string message) 
    { 
     Message = message; 
    } 

    [DataMember] 
    public string Message { get; set; } 
} 

class SampleService : ISampleService 
{ 
    public string SampleMethod(string msg) 
    { 
     throw new FaultException<MyFaultMessage>(new MyFaultMessage("An error occurred.")); 
    }   
} 

此外,您可以在服务器中它的FaultExceptions返回异常细节的配置文件中指定,但这不是在生产中的应用推荐:

<serviceBehaviors> 
    <behavior> 
    <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> 
     <serviceDebug includeExceptionDetailInFaults="true"/> 
    </behavior> 
</serviceBehaviors> 

之后,您可以重写您的处理异常的方法:

var faultException = error as FaultException; 
if (faultException == null) 
{ 
    //If includeExceptionDetailInFaults = true, the fault exception with details will created by WCF. 
    return; 
} 
MessageFault messageFault = faultException.CreateMessageFault(); 
fault = Message.CreateMessage(version, messageFault, faultException.Action); 

客户:

try 
{ 
    _client.SampleMethod(); 
} 
catch (FaultException<MyFaultMessage> e) 
{ 
    //Handle    
} 
catch (FaultException<ExceptionDetail> exception) 
{ 
    //Getting original exception detail if includeExceptionDetailInFaults = true 
    ExceptionDetail exceptionDetail = exception.Detail; 
} 
0

FaultException有一个Code属性,您可以使用前面的异常处理。

try 
{ 
... 
} 
catch (FaultException ex) 
{ 
    switch(ex.Code) 
    { 
     case 0: 
      break; 
     ... 
    } 
} 
7

这篇文章可以帮助:

http://www.olegsych.com/2008/07/simplifying-wcf-using-exceptions-as-faults/

我已经取得了一些成功使用时,我不想列举的例外可能的方法抛出的是创建一个PassthroughExceptionHandlingBehavior类,它为客户端实现服务器端和IClientMessageInspector的IErrorHandler行为。 IErrorHandler行为将异常序列化到故障消息中。 IClientMessageInspector反序列化并抛出异常。

您必须将此行为附加到WCF客户端和WCF服务器。您可以使用配置文件或通过将[PassthroughExceptionHandlingBehavior]属性应用于您的合同来附加行为。

这里的行为类:

public class PassthroughExceptionHandlingBehavior : Attribute, IClientMessageInspector, IErrorHandler, 
    IEndpointBehavior, IServiceBehavior, IContractBehavior 
{ 
    #region IClientMessageInspector Members 

    public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState) 
    { 
     if (reply.IsFault) 
     { 
      // Create a copy of the original reply to allow default processing of the message 
      MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue); 
      Message copy = buffer.CreateMessage(); // Create a copy to work with 
      reply = buffer.CreateMessage();   // Restore the original message 

      var exception = ReadExceptionFromFaultDetail(copy) as Exception; 
      if (exception != null) 
      { 
       throw exception; 
      } 
     } 
    } 

    public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel) 
    { 
     return null; 
    } 

    private static object ReadExceptionFromFaultDetail(Message reply) 
    { 
     const string detailElementName = "detail"; 

     using (XmlDictionaryReader reader = reply.GetReaderAtBodyContents()) 
     { 
      // Find <soap:Detail> 
      while (reader.Read()) 
      { 
       if (reader.NodeType == XmlNodeType.Element && 
        detailElementName.Equals(reader.LocalName, StringComparison.InvariantCultureIgnoreCase)) 
       { 
        return ReadExceptionFromDetailNode(reader); 
       } 
      } 
      // Couldn't find it! 
      return null; 
     } 
    } 

    private static object ReadExceptionFromDetailNode(XmlDictionaryReader reader) 
    { 
     // Move to the contents of <soap:Detail> 
     if (!reader.Read()) 
     { 
      return null; 
     } 

     // Return the deserialized fault 
     try 
     { 
      NetDataContractSerializer serializer = new NetDataContractSerializer(); 
      return serializer.ReadObject(reader); 
     } 
     catch (SerializationException) 
     { 
      return null; 
     } 
    } 

    #endregion 

    #region IErrorHandler Members 

    public bool HandleError(Exception error) 
    { 
     return false; 
    } 

    public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault) 
    { 
     if (error is FaultException) 
     { 
      // Let WCF do normal processing 
     } 
     else 
     { 
      // Generate fault message manually including the exception as the fault detail 
      MessageFault messageFault = MessageFault.CreateFault(
       new FaultCode("Sender"), 
       new FaultReason(error.Message), 
       error, 
       new NetDataContractSerializer()); 
      fault = Message.CreateMessage(version, messageFault, null); 
     } 
    } 

    #endregion 

    #region IContractBehavior Members 

    public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) 
    { 
    } 

    public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime) 
    { 
     ApplyClientBehavior(clientRuntime); 
    } 

    public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime) 
    { 
     ApplyDispatchBehavior(dispatchRuntime.ChannelDispatcher); 
    } 

    public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint) 
    { 
    } 

    #endregion 

    #region IEndpointBehavior Members 

    public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) 
    { 
    } 

    public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime) 
    { 
     ApplyClientBehavior(clientRuntime); 
    } 

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher) 
    { 
     ApplyDispatchBehavior(endpointDispatcher.ChannelDispatcher); 
    } 

    public void Validate(ServiceEndpoint endpoint) 
    { 
    } 

    #endregion 

    #region IServiceBehavior Members 

    public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) 
    { 
    } 

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase) 
    { 
     foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers) 
     { 
      ApplyDispatchBehavior(dispatcher); 
     } 
    } 

    public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase) 
    { 
    } 

    #endregion 

    #region Behavior helpers 

    private static void ApplyClientBehavior(System.ServiceModel.Dispatcher.ClientRuntime clientRuntime) 
    { 
     foreach (IClientMessageInspector messageInspector in clientRuntime.MessageInspectors) 
     { 
      if (messageInspector is PassthroughExceptionHandlingBehavior) 
      { 
       return; 
      } 
     } 

     clientRuntime.MessageInspectors.Add(new PassthroughExceptionHandlingBehavior()); 
    } 

    private static void ApplyDispatchBehavior(System.ServiceModel.Dispatcher.ChannelDispatcher dispatcher) 
    { 
     // Don't add an error handler if it already exists 
     foreach (IErrorHandler errorHandler in dispatcher.ErrorHandlers) 
     { 
      if (errorHandler is PassthroughExceptionHandlingBehavior) 
      { 
       return; 
      } 
     } 

     dispatcher.ErrorHandlers.Add(new PassthroughExceptionHandlingBehavior()); 
    } 

    #endregion 
} 

#region PassthroughExceptionHandlingElement class 

public class PassthroughExceptionExtension : BehaviorExtensionElement 
{ 
    public override Type BehaviorType 
    { 
     get { return typeof(PassthroughExceptionHandlingBehavior); } 
    } 

    protected override object CreateBehavior() 
    { 
     System.Diagnostics.Debugger.Launch(); 
     return new PassthroughExceptionHandlingBehavior(); 
    } 
} 

#endregion 
+0

什么方法火的HandleError后? – KumarHarsh

+0

我可以仅在客户端附加错误处理程序吗?我想将它附加到'ClientBase '实现,而不是服务级别,这可能吗? – Shimmy

+0

当然。我使用了一个辅助方法,如下所示: var factory = new ChannelFactory (binding,endpointAddress); factory.Endpoint.EndpointBehaviors.Add(new PassthroughExceptionHandlingBehavior()); return factory.CreateChannel(); –