1

我想像这样使用custome FaultException

 [DataContract]
public class Fault
{
    [DataMember]
    public string Message { get; set; }
}

public class MyFault<T>:FaultException<T> where T : Fault
{
     public MyFault(T faultClass)
        : base(faultClass, new FaultReason(faultClass.Message))
    {

    }
}

...

throw new MyFault<Fault>(new Fault {Message = "hello"});

...

界面

[OperationContract]
[FaultContract(typeof(Fault))]
string GetData2(int value);

但是当它到达客户端时,它会转换为 FaultException

      try
        {
            var res = serv.GetData2(1);
        }
        catch (MyFault<WcfService1Sample.Fault> ex)
        {
            label1.Text = ex.Reason.ToString(); //-> i want here
        }
        catch (FaultException<ServiceReference1.Fault> ex)
        {
            label1.Text = ex.Reason.ToString(); //-> catch here
        }
        catch (Exception)
        {

            throw;
        }

我可以在 clint 上发现自定义错误吗?或 WCF 自动将其转换为 FaultException 我如何解决此问题

谢谢 kfir

4

1 回答 1

1

There are two issues, I think. First:

  • What shambulator said: Your custom Fault class must be
    • a DataContract, and use
    • DataMember to mark all properties that shall be serialized.

If this is done, then WCF will

  • translate a service-side throw new FaultException<MyFault>(new MyFault { ... }); into a message which contains your fault, including the data; and
  • translate this fault on the client-side to a FaultException<MyFault>.

Second:

This client-side FaultException<> is generated by WCF. Maybe one can register a custom Exception-Translator, but I have never used it, never needed it, and not found such a thing after a one-minute Google search. I'd recommend just going with the FaultException plus custom Fault-type.

于 2012-08-29T09:57:16.343 回答