tags:

views:

36

answers:

2

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.

+3  A: 

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 are "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).

Marc

marc_s
+1  A: 

In WCF you use FaultException. See for example here.

Konamiman