DotNet, WCF

Throwing Exceptions from WCF Service (FaultException)


Handling exceptions in WCF service is different than usual exceptions handling in .Net. If service raise exception it should propagate to clients and properly handle by client application. Since Exception object is .Net specific so it cannot propagate to clients because clients can be of different technologies, so to propagate to all kinds of clients it should be converted to generic exceptions which can be understand by clients.SoapFault is technology independent and industry accepted based exception which can be any clients. SoapFault Carries error and status information within a SOAP message.

.Net has FaultException<T> generic class which can raise SoapFault exception. Service should throw FaultException<T> instead of usual CLR Exception object. T can be any type which can be serialized.

Now I’ll cover one example to show how service can throw fault exception and same can catch on client.

First I create Service Contract IMarketDataProvider which is having operation contract GetMarketPrice which provide market data of instrument.

IMarketDataProviderService

[ServiceContract]
    public interface IMarketDataProvider
    {

        [FaultContract(typeof(ValidationException))]
        [OperationContract]
        double GetMarketPrice(string symbol);
       
    }

Here is implementation of IMarketDataProviderService interface

public class MarketDataProviderService : IMarketDataProvider
    {
        
       public double GetMarketPrice(string symbol)
        {
            //TODO: Fetch market price
            //sending hardcode value
            if (!symbol.EndsWith(".OMX"))
                throw new FaultException(
		new ValidationException { ValidationError = "Symbol is not valid" }, 
		new FaultReason("Validation Failed"));

            return 34.4d;
        }
    }

Operation contract which might raise exception should have FaultContract attribute

[FaultContract(typeof(ValidationException))]

ValidationException is class which will be encapsulated in FaultException object

To raise exception you need to throw FaultException object in which you need to provide ValidationException in constructor and you can also supply FaultReason.

throw new FaultException(new ValidationException { 
ValidationError = "Symbol is not valid" }, 
new FaultReason("Validation Failed"));

NOTE: ValidationException class should have DataContract to serialize and send to client.

 

[DataContract]
public class ValidationException
  {
       [DataMember]
       public string ValidationError { get; set; }
 }

Catch exception in client Application

You should catch exception as FaultException for service exception.

 

	    try
            {
                var client = new ServiceReference1.MarketDataProviderClient();
                double price=client.GetMarketPrice("MSFT");
                
            }
            catch (FaultException ex)
            {
                Console.WriteLine(ex.Detail.ValidationError);
            }

Output

image

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s