Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF web service call - which exception(s) to catch?

I have a program that calls an external web service, and I want to present the user with a friendly dialog if e.g. the server is down, someone cut the cable etc. Assuming the following code

try {
   client.MyWebService()
}
catch(? ex)
{
   // display friendly dialog explaining what went wrong
}

what exception(s) should I put in place of the question mark in the code? It is kind of hard to actually test situations like this when everything is working smoothly and I have no control over the external part, so some insight would be appreciated.

Thanks!

like image 380
Eyvind Avatar asked Mar 21 '11 06:03

Eyvind


1 Answers

The first thing to do is take advantage of the .Faulted event on your proxy, which you can wire up like this:

((ICommunicationObject)client).Faulted += new EventHandler(client_Faulted);

In your client_Faulted event handler you can then try re-connecting, or shifting to a backup server, or disabling the UI, logging the error, or displaying a message there.

It's obviously still good practice to wrap each call in a try-catch as well, but the .Faulted event can let you deal with most channel problems even earlier.

As for the exception itself, you can have your service throw a FaultException that gets passed back to the client with the details you provide. See an example of its use at this blog posting.

You won't get a FaultException if the channel itself fails (FaultException is a way for the server to communicate its own internal faults to the client).

For channel faults, you may get a CommunicationException or TimeoutException.

Finally, take a look at this project on Codeplex for generating Exception Handling WCF proxies. It may give you a more flexible way of handing faults.

like image 134
Chris Wenham Avatar answered Sep 19 '22 12:09

Chris Wenham