Flattening of AggregateExceptions for Processing

前端 未结 5 824
暖寄归人
暖寄归人 2020-12-10 01:46

I\'m running into a few issues where I call flatten on an AggregateException, but inside there is still ANOTHER AggregateException! T

5条回答
  •  不思量自难忘°
    2020-12-10 02:09

    Keep in mind that the 'flatten' method will give you a list of Exceptions, but can still leave you with a flattened InnerExceptions inside of each Exception.

    So I found that this was not really sufficient:

    try
    {
        // something dangerous
    }
    catch (AggregateException ae)
    { 
        foreach(Exception innerException in ae.Flatten().InnerExceptions)
        {
            Console.WriteLine(innerException.Message());
        }
    }
    

    Because this exception:

    System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.42.55:443 at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) --- End of inner exception stack trace ---

    Would end up like this:

    An error occurred while sending the request.

    The fix was something like this:

    foreach(Exception exInnerException in aggEx.Flatten().InnerExceptions)
    {
        Exception exNestedInnerException = exInnerException;
        do
        {
            if (!string.IsNullOrEmpty(exNestedInnerException.Message))
            {
                Console.WriteLine(exNestedInnerException.Message);
            }
            exNestedInnerException = exNestedInnerException.InnerException;
        }
        while (exNestedInnerException != null);
    }
    

    Resulting in:

    An error occurred while sending the request.

    Unable to connect to the remote server

    A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.42.54:443

    Hope that helps someone.

提交回复
热议问题