0

I'm using webservice to call other services. And I have to call many services with loop.

Now the problem is when some services didn't available, the loop was broke.

HttpWebRequest request = WebRequest.Create(stringBuilder.ToString()) as HttpWebRequest;
request.ContentType = "application/json; charset=utf-8";
request.Credentials = CredentialCache.DefaultCredentials;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
    continue;
}

when the services didn't available(Error 500) it's broken before I have checked statusCode.

Error at response = (HttpWebResponse)request.GetResponse();

How can I check the error and continue to call with the other services?

OammieR
  • 2,800
  • 5
  • 30
  • 51

1 Answers1

2

This is by design and well explained in the documentation, see: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx

If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.

Making your code look something like:

HttpWebRequest request = WebRequest.Create(stringBuilder.ToString()) as HttpWebRequest; 
request.ContentType = "application/json; charset=utf-8"; 
request.Credentials = CredentialCache.DefaultCredentials; 
try
{
    response = (HttpWebResponse)request.GetResponse(); 

    // perform normal processing
}
catch(WebException ex)
{
    // are you sure you just want to swallow the exception like this?
    continue;
}
Polity
  • 14,734
  • 2
  • 40
  • 40