Skip to content

Instantly share code, notes, and snippets.

@KennyBu
Created December 18, 2013 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KennyBu/8023552 to your computer and use it in GitHub Desktop.
Save KennyBu/8023552 to your computer and use it in GitHub Desktop.
An extension method to flatten Exceptions with InnerExceptions
public static class ExceptionExtensions
{
public static IEnumerable<Exception> FlattenHierarchy(this Exception ex)
{
if (ex == null)
{
throw new ArgumentNullException("ex");
}
var innerException = ex;
do
{
yield return innerException;
innerException = innerException.InnerException;
}
while (innerException != null);
}
}
[TestFixture]
public class ExceptionExtensionsTests
{
[Test]
public void GetInnerExceptionMessage()
{
const string test = "This is the base exception This is the inner exception";
var message = string.Empty;
try
{
var innerException = new Exception("This is the inner exception");
throw new Exception("This is the base exception",innerException);
}
catch (Exception exception)
{
var list = exception.FlattenHierarchy();
foreach (var exception1 in list)
{
message = string.Concat(message, exception1.Message);
message = string.Concat(message, " ");
}
}
finally
{
Assert.IsTrue(!string.IsNullOrWhiteSpace(message));
Assert.IsTrue(test == message.Trim());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment