What exception type should be thrown with a WCF Service?

后端 未结 2 1711
陌清茗
陌清茗 2021-01-03 01:25

I\'m converting code from ASMX to WCF. In my ASMX web services I throw back SOAP exceptions like:

if (ex.InnerException != null)
                {
                   


        
相关标签:
2条回答
  • 2021-01-03 01:38

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

    0 讨论(0)
  • 2021-01-03 01:47

    In WCF you use FaultException. See for example here.

    0 讨论(0)
提交回复
热议问题