I have a WCF service that if something goes wrong throws a generic FaultException. I don't know why, sometimes the clients will catch a non-generic FaultException instead of the generic exception.
Does anybody know, what the problem is?
Your service needs to handle all exceptions and wrap them into FaultException<T> where T is a data contract you have written. So the first step is to define a custom data contract that will contain your exception information:
[DataContract]
public class CustomFault
{
public string Message { get; set; }
}
Then you instruct your service contract that its methods could potentially throw FaultException<CustomFault>. This allows the service to expose the CustomFault class in the wsdl, so that clients could generate a proxy class:
[ServiceContract]
public interface IMyServiceContract
{
[FaultContract(typeof(CustomFault))]
void MyMethod(string someArgument);
}
Next step is to implement this interface:
public class MyService : IMyServiceContract
{
public void MyMethod(string someArgument)
{
// Do something here that could throw exceptions but don't catch yet
}
}
To handle exceptions you could implement IErrorHandler which will be used whenever one of your service methods throws an exception. The purpose of this error handler is to wrap the exception into FaultException<CustomFault>:
public class MyErrorHandler : IErrorHandler
{
public bool HandleError(Exception error)
{
return true;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message msg)
{
var customFault = new CustomFault()
{
Message = error.Message,
};
var fe = new FaultException<CustomFault>(customFault);
MessageFault fault = fe.CreateMessageFault();
string ns = "http://somenamespace/whatever";
msg = Message.CreateMessage(version, fault, ns);
}
}
Once you have registered your error handler, on the client side, you will always get FaultException<CustomFault>.
If your client doesn't have access to the Exception type itself (the < T> on FaultException< T>) then the non-generic version of the FaultException is thrown. I just spent hours trying to figure this out, and eventually realized it when I found this on the msdn forums. It would be great if there was some indication that the exception was changed before throwing it out of the service, but there isn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With