I have created a WCF data service with a service operation.
I want to generate a kind of Business exception. I try to generate WebFaultException
but I don't see how to catch this error at the client side when this error is throwing by a service operation.
Here is my service operation to simulate an exception:
[WebGet]
public void GenerateException()
{
throw new DataServiceException( 403, "Custom Message" );
}
Here is my client:
WebClient wc = new WebClient();
wc.DownloadString(
new Uri(
"http://localhost:27820/WcfDataService1.svc/GenerateException"
)
);
DownloadString
is throwing an exception, but it's only Internal Server Error
, I can't see my Custom Message
.
Any Idea ?
Many Thanks.
It is best to throw a DataServiceException. The WCF Data Service runtime knows how to map the properties to the HTTP response and will always wrap it in a TargetInvocationException.
You can then unpack this for the client consumer by overriding the HandleException in your DataService like so:
/// <summary>
/// Unpack exceptions to the consumer
/// </summary>
/// <param name="args"></param>
protected override void HandleException(HandleExceptionArgs args)
{
if ((args.Exception is TargetInvocationException) && args.Exception.InnerException != null)
{
if (args.Exception.InnerException is DataServiceException)
args.Exception = args.Exception.InnerException as DataServiceException;
else
args.Exception = new DataServiceException(400, args.Exception.InnerException.Message);
}
}
You can use WCF FaultContract Attribute to throw and handle a businzess exception.
Refer Link, Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With