6
votes

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.

3
Hi, did you ever find a solution to your problem? I am in the exact same situation and I've got nothing :/Mathieu

3 Answers

3
votes

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);
        }
    }
3
votes

You can use WCF FaultContract Attribute to throw and handle a businzess exception.

Refer Link, Example

0
votes

I solved my 403 error using Set EntitySetAccessRule to AllRead:

         config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);