【问题标题】:Exception handling with WCF Data ServicesWCF 数据服务的异常处理
【发布时间】:2010-08-17 10:58:50
【问题描述】:

我想自定义从我的 WCF 数据服务抛出的异常/错误,以便客户尽可能多地获得有关究竟出了什么问题/缺少什么的信息。关于如何实现这一点的任何想法?

【问题讨论】:

    标签: exception-handling wcf-data-services


    【解决方案1】:

    您需要做一些事情来确保异常通过 HTTP 管道冒泡到客户端。

    1. 您必须为您的 DataService 类添加以下属性:

      [ServiceBehavior(IncludeExceptionDetailInFaults = true)] 公共类 MyDataService : 数据服务

    2. 您必须在配置中启用详细错误:

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

    最好把DataServiceException扔进去。 WCF 数据服务运行时知道如何将属性映射到 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);
        }
    }
    

    更多信息请参见here...

    【讨论】:

      【解决方案2】:

      你可以像这样使用这个属性 ServiceBehaviorAttribute 来装饰你的服务类:

       [ServiceBehavior(IncludeExceptionDetailInFaults=true)]
       public class PricingDataService : DataService<ObjectContext>, IDisposable
       {
         ...
       }
      

      【讨论】:

        【解决方案3】:

        您需要为此创建自定义例外。 请在此处阅读此帖子:Why Create Custom Exceptions?

        您正在使用哪种语言进行开发?

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

        【讨论】:

        • 我正在使用 C# 进行开发。但是,我从服务中抛出的异常不会到达使用该服务的客户端。
        【解决方案4】:

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

        他可能想了解如何告诉使用 WCF 数据服务的客户端在服务器(服务)端抛出/捕获异常时出现了问题(以及发生了什么)。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-20
          • 2011-10-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多