Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF have exception pass to the client

Tags:

exception

wcf

I have a service that may throw exceptions. I want to be able to catch the exceptions at the client. The main Exceptions I am interested in are DbUpdateException and InvalidOperationException. For the rest of the exceptions it is enough to know that an exception has been throws.

How can I have exceptions caught in the client?

like image 829
Ryan Avatar asked Feb 22 '11 10:02

Ryan


People also ask

Which type of exception can be thrown from WCF service?

Fault exceptions are exceptions that are thrown by a WCF service when an exception occurs at runtime -- such exceptions are typically used to transmit untyped fault data to the service consumers.

Which property must be set in WCF configuration to allow users to see exception details of a WCF methods?

It is mandatory to provide the typeof property with FaultContract. Also, if no fault contract attribute is applied, the default exception that will be returned by WCF will be of type FaultException. Run the WCF test client and invoke the method. We can see the details of the custom message that we set.

How do you handle a fault exception in C#?

In a service, use the FaultException class to create an untyped fault to return to the client for debugging purposes. In a client, catch FaultException objects to handle unknown or generic faults, such as those returned by a service with the IncludeExceptionDetailInFaults property set to true .


2 Answers

If your WCF service throws an exception, then by default it will come to the client as a FaultException. You can configure your service to include exception details in faults, like so:

<serviceDebug includeExceptionDetailInFaults="true" />

But you probably don't want to do this, it's never a good idea to expose internal implementation details to clients.

If you want to distinguish between different service faults, you can create your own class, and register this as a fault that your service will throw. You can do this at the service contract level:

public interface YourServiceContract
{
   [FaultContract(typeof(YourFaultClass))]
   [OperationContract(...)]
   YourServiceResponseClass YourServiceOperation(YourServiceRequestClass request);
}

The class you use for your fault contract doesn't have to implement anything (as you would have to do for a custom Exception), it will just get wrapped in a generic FaultContract object. You can then catch this in the client code like this:

try
{
   // service operation
}
catch (FaultException<YourFaultClass> customFault)
{
   ...
}
catch (FaultException generalFault)
{
   ...
}
like image 144
Graham Clark Avatar answered Sep 19 '22 13:09

Graham Clark


Define a FaultContract so any clients can listen for that and include only the exception details you want to expose publicly.

Read this for more info: MSDN Docs

like image 25
Henric Avatar answered Sep 22 '22 13:09

Henric