This is a mirror of official site: http://jasper-net.blogspot.com/

Throwing Exceptions from WCF Service (FaultException)

| Thursday, October 6, 2011
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))]


Read more: Beyond Relational
QR: throwing-exceptions-from-wcf-service-faultexception.aspx

Posted via email from Jasper-net

0 comments: