Proper catching of specific exceptions through web service

前端 未结 2 1837
渐次进展
渐次进展 2021-01-16 05:47

I am currently using a C# .NET Service in our client program. As part of the server design, several custom made exceptions are thrown to indicate specific errors (as in any

相关标签:
2条回答
  • 2021-01-16 06:13

    The proper way would be to define fault contracts. For example in your web service you could do the following:

    [DataContract]
    public class NoRoomsAvailableFaultContract
    {
        [DataMember]
        public string Message { get; set; }
    }
    

    Next you declare this contract for a given service operation

    [ServiceContract]
    public interface IMyServiceContract
    {
        [OperationContract]
        [FaultContract(typeof(NoRoomsAvailableFaultContract))]
        void MyOperation();
    }
    

    And you implement it like so:

    public class MyService : IMyServiceContract 
    {
        public void MyOperation()
        {
            if (somethingWentWrong)
            {
                var faultContract = new NoRoomsAvailableFaultContract()
                {
                    Message = "ERROR MESSAGE"
                };
                throw new FaultException<NoRoomsAvailableFaultContract>(faultContract);
            }
        }
    }
    

    In this case the NoRoomsAvailableFaultContract will be exposed in the WSDL and svcutil.exe could generate a proxy class. Then you could catch this exception:

    try
    {
        myServiceProxy.MyOperation();
    }
    catch (FaultException<NoRoomsAvailableFaultContract> ex)
    {
        Console.WriteLine(ex.Message);
    }
    
    0 讨论(0)
  • 2021-01-16 06:22

    darin has the correct answer. I'll only say explicitly what he implies: web services do not pass exceptions. They return SOAP Faults. If you define your faults properly, as he does, then you get to throw FaultException<fault>. This will become a SOAP Fault with fault in the detail element. In the case of a .NET client, this will then be turned into a FaultException<fault>, which you can catch.

    Other platforms may handle this somewhat differently. I've seen IBM's Rational Web Developer generate Java proxy code that creates a separate exception for each declared fault. That was a version before Java generics, so maybe by now it does the same thing as .NET does.

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