I'm converting code from ASMX to WCF. In my ASMX web services I throw back SOAP exceptions like:
if (ex.InnerException != null)
{
SoapException se = new SoapException(ex.Message, SoapException.ServerFaultCode, Context.Request.Url.AbsoluteUri, ex.InnerException);
throw se;
}
What kind of exceptions should I throw back to WCF clients calling my service? I am guessing the SOAP exceptin is the wrong kind, because the test client doesn't see it as a valid error, and just says - internal error occurred in the web service.
Fault exceptions are exceptions that are thrown by a WCF service when an exception occurs at runtime -- such exceptions are typically used to transmit untyped fault data to the service consumers.
Fault exception in WCF. It is used in a client application to catch contractually-specified SOAP faults. By the simple exception message, you can't identify the reason of the exception, that's why a Fault Exception is useful.
It is mandatory to provide the typeof property with FaultContract. Also, if no fault contract attribute is applied, the default exception that will be returned by WCF will be of type FaultException. Run the WCF test client and invoke the method. We can see the details of the custom message that we set.
C# exception handling is built upon four keywords: try, catch, finally, and throw.
Basically, in a WCF service, you're best off when you only throw FaultException
(or FaultException<T>
).
This is because of two things: since WCF is designed to be interoperable (your client could easily be a non-.NET app), you should not use .NET exceptions - those are too platform-specific. And two: if you use FaultExceptions (which are translated into SOAP faults), your channel (the connection between client and server) will not be torn down, or "faulted". The WCF runtime on the server side treats all non-handled .NET exceptions as "severe" exceptions and thus puts the channel in a faulted state, assuming something really bad has happened.
If your channel is faulted, you cannot use it anymore - you'll have to close your client proxy and re-create it from scratch.
If you want to (or have to) be very interoperable, you would define your SOAP faults are fault contracts (analogous to data contracts) in a separate file, and then you'd throw FaultException<T>
where T would be one of your fault contracts. If you're strictly .NET on either side, you can also stick .NET exceptions into FaultException as generic type T, if you want to - the channel won't be faulted (e.g. you could throw a FaultException<InvalidOperationException>
and thus signal back what went wrong).
In WCF you use FaultException
. See for example here.
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