I’d like to throw custom exception from WCF server but it doesn’t work well for my clients. What I do:
My custom exception:
[DataContract]
public class MyCustomException
{
[DataMember]
public string MyField { get; set; }
}
My WCF service contract
[ServiceContract]
public interface IMyService
{
[OperationContract]
[FaultContract(typeof(MyCustomException))]
bool Foo();
}
My global exception handler for WCF service (this code hits when Foo is called):
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
);
}
Then… my client:
try
{
Create channel factory and call Foo
}
catch(FaultException<MyCustomException> ex)
{
// OOOPS! It doesn't work!!!
}
catch(FaultException ex)
{
// This block catches exception
}
What can be wrong here? Thank you in advance!
I’ve found the issue in
ProvideFaultmethod:should be replaced with
Now everything comes ok!