简体   繁体   中英

Capturing SOAP faults and handling exceptions

I am consuming a web services. Some methods throw exception when i invoked, because the parameters are invalid values, for example. I want to handle the exceptions but it don't contains any data information, only the message "Bad Request". This is my http response: 在此输入图像描述

        try
        {
            var data = client.SomeMethod(4);
        }
        catch (Exception exception)
        {
            // exception.Message = Bad Request
            // exception don't contains any more data information
        }   

How can I capture the other information

You can catch the exception with FaultException when the http status code is 2xx or 5xx, not 4xx. You can catch the http status code 4xx with System.ServiceModel.ProtocolException and then get the stream from the InnerException and parse it or get the FaultException from this stream. See http://blogs.msdn.com/b/nathana/archive/2011/03/31/deciphering-a-soap-fault-with-a-400-status-code.aspx for more details.

I'm assuming this is a WCF web service? You are catching to wide of an exception. Try with a FaultException<TDetail> .

Typical deployed services use the FaultContractAttribute to formally specify all SOAP faults that a client can expect to receive in the normal course of an operation. Error information in a FaultContractAttribute appears as a FaultException (where the typeparameter is the serializable error object specified in the operation's FaultContractAttribute) when it arrives at a client application. The FaultContractAttribute can be used to specify SOAP faults for both two-way service methods and for asynchronous method pairs.

Because FaultException is both a FaultException and therefore a CommunicationException, to catch specified SOAP faults make sure you catch the FaultException types prior to the FaultException and CommunicationException types or handle the specified exceptions in one of those exception handlers.

You can use try-catch like below. Then you can access other information. You have to find the "TDetail". It provides by the web service.

catch(FaultException<TDetail> ex)
{
    ex.Code.ToString();
    ex.Reason.ToString();
}

Other way.

FaultException faultException = (FaultException)ex;
MessageFault msgFault = faultException.CreateMessageFault();
XmlElement elm = msgFault.GetDetail<XmlElement>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM