Is there any way to write a LINQ style "short hand" code for walking to all levels of InnerException(s) of Exception thrown? I would prefer to write it in place instead of calling an extension function (as below) or inheriting the Exception
class.
static class Extensions { public static string GetaAllMessages(this Exception exp) { string message = string.Empty; Exception innerException = exp; do { message = message + (string.IsNullOrEmpty(innerException.Message) ? string.Empty : innerException.Message); innerException = innerException.InnerException; } while (innerException != null); return message; } };
When you're debugging and you get an exception, always, always, always click on the View Details link to open the View Details dialog. If the message in the dialog isn't expanded, expand it, then scan down to the Inner Exception entry.
To get the type of the exception, we can invoke the GetType() method from the Exception class object and then we can invoke the Name property to get the name of the exception. To write the exception details in a file, the StreamWriter provides a method “write” or “writeline” of which we can pass the ex. GetType().
Exception. An object that describes the error that caused the current exception. The InnerException property returns the same value as was passed into the Exception(String, Exception) constructor, or null if the inner exception value was not supplied to the constructor. This property is read-only.
If you want information about all exceptions then use exception. ToString() . It will collect data from all inner exceptions. If you want only the original exception then use exception.
Unfortunately LINQ doesn't offer methods that could process hierarchical structures, only collections.
I actually have some extension methods that could help do this. I don't have the exact code in hand but they're something like this:
// all error checking left out for brevity // a.k.a., linked list style enumerator public static IEnumerable<TSource> FromHierarchy<TSource>( this TSource source, Func<TSource, TSource> nextItem, Func<TSource, bool> canContinue) { for (var current = source; canContinue(current); current = nextItem(current)) { yield return current; } } public static IEnumerable<TSource> FromHierarchy<TSource>( this TSource source, Func<TSource, TSource> nextItem) where TSource : class { return FromHierarchy(source, nextItem, s => s != null); }
Then in this case you could do this to enumerate through the exceptions:
public static string GetaAllMessages(this Exception exception) { var messages = exception.FromHierarchy(ex => ex.InnerException) .Select(ex => ex.Message); return String.Join(Environment.NewLine, messages); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With