Created
December 18, 2013 14:50
-
-
Save KennyBu/8023552 to your computer and use it in GitHub Desktop.
An extension method to flatten Exceptions with InnerExceptions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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