Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF Data Service Error Handling

Tags:

wcf

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.

like image 958
pierre_charlesp1980 Avatar asked Mar 02 '11 08:03

pierre_charlesp1980


2 Answers

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);
        }
    }
like image 89
jaimie Avatar answered Sep 24 '22 23:09

jaimie


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

Refer Link, Example

like image 39
Milan Raval Avatar answered Sep 21 '22 23:09

Milan Raval