【问题标题】:Exceptions in WCF servicesWCF 服务中的异常
【发布时间】:2017-06-13 01:08:57
【问题描述】:

我的ServiceBase 抽象类中有以下代码:

    internal ServiceResponse ExecuteNonQuery(Action action)
    {
        try
        {
            action();
            return new ServiceResponse() { IsFaulty = false };
        }
        catch (DbEntityValidationException e)
        {
            OnDbEntityValidationException(e);
            return new ServiceResponse() { IsFaulty = true, Exception = e};
        }
        catch (Exception e)
        {
            _logger.Log(e);
            return new ServiceResponse() {IsFaulty = true, Exception = e};
        }
    }

我的所有服务都派生自此类,我的 WCF 服务端点如下所示:

    public ServiceResponse Add(Client client)
    {
        _logger.LogInformation($"ClientService.Add()");
        return ExecuteNonQuery(() =>
        {
            using (var context = _contextFactory.Build())
            {
                context.Clients.Add(_serviceToDalMapper.Map(client));
                context.SaveChanges();
            }
        });
    }

在客户端调用我的服务时,我有类似的 Try/Catch 方法。

我不明白的是,当服务端抛出异常时,异常被捕获,但我仍然在客户端得到一个System.ServiceModel.CommunicationException。为什么 ?我发现了我的异常,我的服务不应该只返回ServiceResponse吗?

【问题讨论】:

  • 可能在catch块内抛出异常

标签: c# asp.net wcf exception


【解决方案1】:

在当前的catch 中添加try-catch,看起来调用正在生成异常,可能在catch 中生成。

 catch (DbEntityValidationException e)
 {
      try
      {
        OnDbEntityValidationException(e);
        return new ServiceResponse() { IsFaulty = true, Excepetion = e};
      }
      catch
      {
        return new ServiceResponse() { IsFaulty = true, Excepetion = new Exception("Error handling the error")};   
      }
 }

【讨论】:

  • 显然 WCF 无法序列化异常,这是我尝试将异常发送回客户端时的问题... thx
  • @EmmanuelIstace 也许你应该检查一下 FaultContract stackoverflow.com/questions/5717231/…
  • 谢谢,在寻找我得到异常的原因时,我发现了 FaultContract 属性,因为这似乎是一个最佳实践,我将在未来使用它:)
  • 对于您希望客户端能够处理的异常,使用 FaultContract 当然是一种很好的做法。但是对于其他技术异常,您可以让异常从您的服务方法传播。您还可以实现 System.ServiceModel.Dispatcher.IErrorHandler(特别是 ProvideFault 方法)以将异常包装在更友好的 FaultException 中。
【解决方案2】:

WCF 无法序列化 Exception 对象(这在某种程度上是有意义的)。

所以在我的 catch 块中抛出了一个异常,这就是这里的错误。

根据 WCF 最佳实践,我应该使用 FaultContract 将异常传达给客户端。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多