WCF中的异常处理问题,尝试捕获不起作用

时间:2011-07-21 09:07:05

标签: wcf exception-handling try-catch

我有一个非常好用的wcf服务(nettcpbinding,duplex)。今天我遇到了一个非常奇怪的问题。以下代码运行正常,如果“new A(”123“);”抛出一个例外,它被抓住了。

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Single)]
public class Service: ITestService
{

  // the interface is defined as [OperationContract(IsOneWay = true)], so fire and forget
  public void Test()
  {
    try
    {
         var t = new A("123");
    }
    catch(Exception ex)
    {}

  }
}

但是,如果我更改A.dll并更改方法参数,我希望得到一个MissingMethodException。我得到的是WCF没什么:( WCF服务只是中止,在客户端我得到了我的WCF频道的Faulted事件。

那为什么我的捕获不起作用? WCF是否以另一种方式处理此类xceptions?

请求帮助

2 个答案:

答案 0 :(得分:2)

尝试启用logging on the WCF Service并查看日志。有些异常不可能在WCF方法或WCF客户端代码中捕获,而是被WCF框架捕获,并且只能通过日志记录找到。

答案 1 :(得分:2)

当您创建A时,失败不会发生,它会在JIT编译Test / catch块之外的方法Test时失败。

如果您将A的创建移动到另一个方法并从try块中调用它,您将捕获异常

像这样的东西

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Single)]
public class Service: ITestService
{

  // the interface is defined as [OperationContract(IsOneWay = true)], so fire and forget
  public void Test()
  {
    try
    {
         var t = GetA("123");
    }
    catch(Exception ex)
    {}

  }

  private A GetA(string s)
  {
      return new A(s);
  }
}