【问题标题】:WCF: can't handle FaultException<T> on a clientWCF:无法在客户端上处理 FaultException<T>
【发布时间】:2011-11-24 11:51:19
【问题描述】:

我想从 WCF 服务器抛出自定义异常,但它不适用于我的客户。我做什么:

我的自定义异常:

[DataContract]    
public class MyCustomException
{
  [DataMember]
  public string MyField { get; set; }
}

我的 WCF 服务合同

[ServiceContract]    
public interface IMyService
{
       [OperationContract]
       [FaultContract(typeof(MyCustomException))]
       bool Foo();
}

我的 WCF 服务全局异常处理程序(调用 Foo 时此代码命中):

public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
{
  var ex = new MyCustomException { MyField = "..." };
  var fe = new FaultException<MyCustomException>(
                    ex,
                    new FaultReason("reason"),
                    FaultCode.CreateSenderFaultCode(new FaultCode("some-string")));

  var flt = fe.CreateMessageFault();
  fault = Message.CreateMessage(
    version,
    flt,
    string.Empty
  );        
}

那么……我的客户:

try
{
   Create channel factory and call Foo
}
catch(FaultException<MyCustomException> ex)
{
  // OOOPS! It doesn't work!!! 
}
catch(FaultException ex)
{
  // This block catches exception 
}

这里有什么问题?先感谢您!

【问题讨论】:

    标签: .net wcf exception-handling


    【解决方案1】:

    我在ProvideFault 方法中发现了问题:

    fault = Message.CreateMessage(
        version,
        flt,
        string.Empty
      ); 
    

    应该替换为

    fault = Message.CreateMessage(
        version,
        flt,
        fe.Action
      ); 
    

    现在一切正常!

    【讨论】:

      猜你喜欢
      • 2013-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多