开发者

WCF Data Service Error Handling

开发者 https://www.devze.com 2023-02-14 02:39 出处:网络
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

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, "Cus开发者_如何学Ctom 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


I solved my 403 error using Set EntitySetAccessRule to AllRead:

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

精彩评论

暂无评论...
验证码 换一张
取 消