.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: