Best way to structure the code that calls a web service

I call a web service through httpwebrequest and get a response. The web service is designed to work 24/7.

What is the best way to structure this code with checking the availability of a “service”?

What I have:

if (NetworkIsAvailable()) { // Call web service // Handle exceptions within here. } else { // to throw a relevant exception that there is no network } 

Is it possible to throw an exception or just return false? Svc should never be lower

+4
source share
1 answer

Depending on the type of data you get back, the frequency of checks, etc., I would use a general-purpose solution that tries to make a connection on failure several times and then classifies the “exceptions” on failure (there are no two exceptions the same in my experience).

For instance:

 var failCount = 0; var succeeded = false; while ((failCount < 3) && (!succceeded)) { try { //call service.... succeeded = true; } catch(WebException wex) { //handle wex, for instance look for timeout and retry } catch(...) { //Handle other exceptions differently... LogError("BOOOM: " + excep); throw; } catch(Exception ex) { //handle a general exception failCount++; } } if (failCount >= 4) { //Unspecified error multiple times, react appropriately... } 

Obviously, you do not want to do this a few attempts, if its an expensive call, here I assume that this is a kind of "heartbeat", it is not too expensive. A “FailCount” can be set up depending on how “turbulent” you expect the connection to be.

+4
source

Source: https://habr.com/ru/post/1393814/


All Articles