Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best approach to handle exceptions in WCF service?

Tags:

I have a WCF service deployed on two or more remote machines and there is a desktop based application that is used by the client to access any wcf service.

The WCF service is connected to SQL server 2005 to read and write data. This is an intranet scenario in which the client should be on same domain.

Now there can be scenarios where the wcf service throws exceptions:

  1. Invalid URL
  2. WCF service is down
  3. SQL server 2005 is not running
  4. Client is not on the same domain
  5. Authentication fails
  6. Authorization fails

and many other exceptions.

For every exception I have to perform some action or update a status bar, depending on the exception. For example if authorization fails I have to prompt the user to re-enter their credentials.

Please suggest the best design approach to handle this.

like image 291
Ashish Ashu Avatar asked Oct 08 '09 07:10

Ashish Ashu


People also ask

What is exception handling in WCF?

Advertisements. A WCF service developer may encounter some unforeseen errors which require reporting to the client in a suitable manner. Such errors, known as exceptions, are normally handled by using try/catch blocks, but again, this is very technology specific.

Which type of behavior should be configured to return exception detail from WCF service?

Since the service and client applications are interacting with each other using SOAP, we need to exception details in SOAP format. We can use FaultException &/or FaultContract (in System. ServiceModel namespace) to these exception details to the client.


1 Answers

You can definitely catch and handle all exceptions that happen on your service class and turn them into a FaultException or FaultException exception.

That way, you won't "fault" (or tear down) the communications channel between your client and server.

Even better approach would be to implement the IErrorHandler interface on your service class that provides a way to globally catch all exceptions as they happen and provide a FaultException instead, that's SOAP compliant.

You can even turn your IErrorHandler into a configurable behavior that can be turned on or off in config.

See these articles and blog posts for more details:

  • Rory Primrose: Implementing IErrorHandler
  • Useful WCF behaviors: IErrorHandler
like image 110
marc_s Avatar answered Oct 02 '22 17:10

marc_s