Proper catching of specific exceptions through web service

前端 未结 2 1838
渐次进展
渐次进展 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(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 ex)
    {
        Console.WriteLine(ex.Message);
    }
    

提交回复
热议问题