AggregateException 没有被捕获?
AggregateException not being caught?
我正在查询远程服务器,有时会得到 AggregateException
。这是相当罕见的,我知道发生这种情况时如何解决,但由于某种原因,每当抛出异常时它都不会进入 catch
块。
这是 catch 块的代码部分:
try
{
using (Stream stream = await MyQuery(parameters))
using (StreamReader reader = new StreamReader(stream))
{
string content = reader.ReadToEnd();
return content;
}
}
catch (AggregateException exception)
{
exception.Handle((innerException) =>
{
if (innerException is IOException && innerException.InnerException is SocketException)
{
DoSomething();
return true;
}
return false;
});
}
这是我收到的异常消息:
System.AggregateException: One or more errors occurred. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
我假设那些 --> 箭头表示这是一个内部异常,对吗?
所以如果它是 IOException -> SocketException,为什么 DoSomething()
从未被调用过?
我怀疑您此时实际上并没有看到 AggregateException
。您所拥有的代码中没有任何内容正在执行并行操作。
如果那是正确的,你应该能够做这样的事情:
try
{
using (Stream stream = await MyQuery(parameters))
using (StreamReader reader = new StreamReader(stream))
{
string content = reader.ReadToEnd();
return content;
}
}
catch (IOException exception)
{
if (exception.InnerException is SocketException)
DoSomething();
else
throw;
}
我正在查询远程服务器,有时会得到 AggregateException
。这是相当罕见的,我知道发生这种情况时如何解决,但由于某种原因,每当抛出异常时它都不会进入 catch
块。
这是 catch 块的代码部分:
try
{
using (Stream stream = await MyQuery(parameters))
using (StreamReader reader = new StreamReader(stream))
{
string content = reader.ReadToEnd();
return content;
}
}
catch (AggregateException exception)
{
exception.Handle((innerException) =>
{
if (innerException is IOException && innerException.InnerException is SocketException)
{
DoSomething();
return true;
}
return false;
});
}
这是我收到的异常消息:
System.AggregateException: One or more errors occurred. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
我假设那些 --> 箭头表示这是一个内部异常,对吗?
所以如果它是 IOException -> SocketException,为什么 DoSomething()
从未被调用过?
我怀疑您此时实际上并没有看到 AggregateException
。您所拥有的代码中没有任何内容正在执行并行操作。
如果那是正确的,你应该能够做这样的事情:
try
{
using (Stream stream = await MyQuery(parameters))
using (StreamReader reader = new StreamReader(stream))
{
string content = reader.ReadToEnd();
return content;
}
}
catch (IOException exception)
{
if (exception.InnerException is SocketException)
DoSomething();
else
throw;
}