Proper way to throw exception over WCF

前端 未结 2 1281
夕颜
夕颜 2020-12-18 02:12

I\'m trying to send exceptions over WCF in the most generic way possible. Here\'s what I\'ve got:

[ServiceContract]
interface IContract
{
    [OperationContr         


        
相关标签:
2条回答
  • 2020-12-18 02:45

    First, in MyException, remove the inheritance from Exception and make it public.

    Second, when you declare your service contract, declare exception as it follows:

    [FaultContractAttribute(
            typeof(MyException),
            Action = "", 
            Name = "MyException", 
            Namespace = "YourNamespace")]
        [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults = true)]
        [OperationContract]
        void Foo()
    

    Finally, you can throw your Exception like this:

    throw new FaultException<MyException>
                 (
                     new MyException(ex.Message),
                     new FaultReason("Description of your Fault")
    
                 );
    

    Hope it helps.

    0 讨论(0)
  • 2020-12-18 02:47

    Firstly - apologies, I would rather post this as a comment and not as an answer. As a relative noob, I am unable to!

    This article discusses in a decent level of detail how to relay exception details back: http://www.codeproject.com/Articles/799258/WCF-Exception-FaultException-FaultContract

    Afaik, you cannot actually pass the exception itself back to the client as an exception is not SOAP compliant. Also consider whether passing the whole exception could compromise the security of your code.

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