I'm trying to create a robust way to pass exceptions from the server to the client but I seem to be missing something.
The intention is to use FaultException
to wrap actual serializable Exception
subclasses caught on the server side, pass them over WCF, then rethrow them at the client side.
Server side code:
[ServiceKnownType(typeof(MyException))]
[ServiceContract]
interface IContract
{
[FaultContract(typeof(MyException))]
[OperationContract]
void Foo();
}
class Service : IContract
{
public void Foo()
{
try
{
Bar();
}
catch (MyException ex)
{
throw new FaultException<MyException>(ex, ex.Message);
}
catch (Exception ex)
{
throw new FaultException(ex.ToString());
}
}
}
Client side code:
try
{
client.Foo();
}
catch (FaultException<MyException> ex)
{
throw ex.Detail;
}
catch (FaultException ex)
{
throw;
}
MyException
:
[Serializable]
public sealed class MyException: Exception
{
public MyException(string description)
: base(description)
{
}
public MyException()
{
}
public MyException(string message, Exception innerException)
: base(message, innerException)
{
}
private MyException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
What I'm observing is that the server side code executes the catch (MyException ex)
block but when the fault gets back to the client side, the code goes into the catch (FaultException ex)
block and rethrows a normal FaultException
, rather than MyException
(interestingly, the FaultException
does contain the message of the original MyException
object).
Note that both the client and server have visibility of MyException
, svcutil generates the correct attributes for the client side service contract and the WCF logs don't show any serialization errors.