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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With