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

前端 未结 3 710
别跟我提以往
别跟我提以往 2021-01-12 20:49

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 th

3条回答
  •  粉色の甜心
    2021-01-12 21:30

    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.

提交回复
热议问题