【问题标题】:Properties of Inner Exception are Disposed?内部异常的属性被处理了吗?
【发布时间】:2011-09-22 17:07:20
【问题描述】:

我正在为 WCF Web 服务编写单元测试。我故意向抛出WebExceptionFault<string> 的服务器发送无效请求。在单元测试中,被捕获的异常是EndpointNotFoundException,在InnerException 属性中具有标准WebException。我想验证响应的正文是否与我认为应该存在的字符串匹配。

不过,我遇到了一个问题,因为WebException(即System.Net.SyncMemoryStream)的Response 属性已释放,无法读取。

我的代码:

Clubs actual;
try
{
    //"201" is an invalid argument for the first parameter
    actual = new Clubs(channel.GetClubs("201", "123"));
}
catch (EndpointNotFoundException e)
{
    WebException w = e.InnerException as WebException;
    Assert.IsNotNull(w);

    HttpWebResponse resp = w.Response as HttpWebResponse;
    Assert.IsNotNull(resp);
    Assert.AreEqual(resp.StatusCode, HttpStatusCode.NotFound);
    //Next line throws an ArgumentException saying Stream not readable
    //Investigation shows it has been disposed
    using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
        Assert.AreEqual(sr.ReadToEnd(), "League not allowed for selected club");
}

InnerException 的属性被释放是否正常?有没有办法解决这个问题?

【问题讨论】:

  • 这是意料之中的。 System.Net 不会假设捕获异常的任何人都会经历挖掘响应流并处理它的麻烦。所以它在扔之前清理干净。您无法更改此行为。
  • 如果底层连接关闭,你肯定不能访问响应流吧?那时,您几乎可以肯定在您开始处理EndPointNotFoundException 异常时已将其关闭。我认为您应该开始处理异常,因为它会立即在响应流中读取并包装起来。
  • @Jeff:上例中底层连接何时关闭?我可以看到读取响应流的最早点是在获得HttpWebResponse 之后。是你的意思吗?
  • 我认为您的构造函数中有一个 using 块用于连接。一旦超出范围,连接将被关闭。如果我对 WCF 或您的情况有一些误解,我深表歉意。
  • @Jeff:是的,我有一个创建通道的 using 语句,但它仍在范围内。 @汉斯:谢谢。我想这回答了我的问题。

标签: c# exception exception-handling inner-exception


【解决方案1】:

似乎是异常序列化问题。您可能必须在服务器上捕获错误并自定义构建错误消息

How to serialize an Exception object in C#?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多