在WCF中抛出具有内部异常的异常

时间:2015-05-13 13:25:53

标签: c# .net wcf exception-handling

我试图通过WCF线路发送异常,但无法弄清楚我做错了什么。 我关注guidance of Oleg SychMSDN,但无济于事。

我得到的是The requested service, 'net.tcp://mymachine/myservicepath/MyService.svc' could not be activated. See the server's diagnostic trace logs for more information.

[ServiceContract]
public interface ISystemInfoService
{
    [OperationContract]
    [FaultContract(typeof(MyException))]
    void DoThrowException(string message);
}

//[ServiceContract]  // <- the culprit
public class SystemInfoService : ISystemInfoService
{
    public void DoThrowException(string message)
    {
        try
        {
            throw new MyException( "MyMessage" );
        }
        catch (MyExceptionexc)
        {
            throw new FaultException<MyException>(exc);
        }
    }
}

// The custom Exception resides in an common assembly reachable from both server and client.
[Serializable]
public class MyException: Exception
{
...
}

TIA

1 个答案:

答案 0 :(得分:1)

您可以尝试使用datacontract类而不是可序列化的异常来处理异常吗?

[DataContract]
public class MyExceptionClass
{
    [DataMember]
    public Exception Exc { get; set; }
}

[ServiceContract]
public interface ISystemInfoService
{
    [OperationContract]
    [FaultContract(typeof(MyExceptionClass))]
    void DoThrowException(string message);
}

public class SystemInfoService : ISystemInfoService
{
    public void DoThrowException(string message)
    {
        try
        {
            throw new Exception("MyMessage");
        }
        catch (Exception exc)
        {
            var data = new MyExceptionClass { Exc = exc };
            throw new FaultException<MyExceptionClass>(data);
        }
    }
}