Derek Patton
Derek Patton

Reputation: 233

AggregateException not being caught?

I'm querying a remote server and sometimes get an AggregateException. This is fairly rare and I know how to get around when this happens, but for some reason, it's not entering the catch block whenever the exception is thrown.

This is the code part for the catch block:

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;
    });
}

And this is the exception message I'm getting:

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 ---

I'm assuming those --> arrows indicate that it's an inner exception right? So if it's IOException -> SocketException, why is DoSomething() never called?

Upvotes: 1

Views: 943

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456477

I suspect you're not actually seeing an AggregateException at this point. There's nothing in the code you have that is doing parallel operations.

If that's correct, you should be able to do something like this:

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;
}

Upvotes: 2

Related Questions