Retrieveing All Exceptions

Do you want to retrieve all the Exceptions, including the inner Exceptions when an Exception is thrown for logging purposes? Since they are not enumerable, I wrote a block of recursive code below that will do the trick.

    1 Function RetrieveAllExceptions(ByVal ex As Exception) As ObjectModel.ReadOnlyCollection(Of Exception)

    2    Dim exceptions As New Generic.List(Of Exception)


    4    If ex IsNot Nothing Then

    5       exceptions.Add(ex)


    7       If ex.InnerException IsNot Nothing Then

    8          exceptions.AddRange(RetrieveAllExceptions(ex.InnerException))

    9       End If

   10    End If


   12    Return New ObjectModel.ReadOnlyCollection(Of Exception)(exceptions)


   14 End Function

Tip Submitted By: David McCarter