使用WCF数据服务进行异常处理

9
我希望能够自定义WCF数据服务抛出的异常/错误,以便客户端尽可能地了解到出了什么问题/缺少什么信息。你有什么想法如何实现这一点?
4个回答

11

确保异常通过HTTP管道传递到客户端,您需要执行以下几步操作:

  1. 在您的DataService类上添加以下属性:

    [ServiceBehavior(IncludeExceptionDetailInFaults = true)] public class MyDataService : DataService

  2. 在配置中启用详细错误信息:

    public static void InitializeService(DataServiceConfiguration config) { config.UseVerboseErrors = true; }

最好在内部抛出DataServiceException。WCF Data Service运行时知道如何将属性映射到HTTP响应,并始终将其包装在TargetInvocationException中。

[WebGet]
public Entity OperationName(string id)
{
    try
    {
        //validate param
        Guid entityId;
        if (!Guid.TryParse(id, out entityId))
            throw new ArgumentException("Unable to parse to type Guid", "id");

        //operation code
    }
    catch (ArgumentException ex)
    {
        throw new DataServiceException(400, "Code", ex.Message, string.Empty, ex);
    }
}

你可以通过在你的DataService中重写HandleException方法,对客户端进行解包并消费异常:

/// <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
您可以使用ServiceBehaviorAttribute属性来装饰您的服务类,如下所示:
 [ServiceBehavior(IncludeExceptionDetailInFaults=true)]
 public class PricingDataService : DataService<ObjectContext>, IDisposable
 {
   ...
 }

0

您需要为此创建自定义异常。

请阅读此处的帖子:为什么要创建自定义异常?

您正在开发哪种语言?

如果您需要进一步指导,请添加一些评论。


我正在使用C#进行开发。然而,我从服务中抛出的异常无法到达消费该服务的客户端。 - Martinfy

0

我认为他不想知道如何在.NET中抛出/捕获异常。

他可能想了解如何告诉消费WCF数据服务的客户端,当服务器(服务)端抛出/捕获异常时,发生了什么(以及什么)。

WCF数据服务使用HTTP请求/响应消息,您不能仅从服务向客户端抛出异常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接