Message
गहरे अपवादों के सिर्फ एक हिस्से को ही प्रिंट करने के लिए , आप ऐसा कुछ कर सकते हैं:
public static string ToFormattedString(this Exception exception)
{
IEnumerable<string> messages = exception
.GetAllExceptions()
.Where(e => !String.IsNullOrWhiteSpace(e.Message))
.Select(e => e.Message.Trim());
string flattened = String.Join(Environment.NewLine, messages); // <-- the separator here
return flattened;
}
public static IEnumerable<Exception> GetAllExceptions(this Exception exception)
{
yield return exception;
if (exception is AggregateException aggrEx)
{
foreach (Exception innerEx in aggrEx.InnerExceptions.SelectMany(e => e.GetAllExceptions()))
{
yield return innerEx;
}
}
else if (exception.InnerException != null)
{
foreach (Exception innerEx in exception.InnerException.GetAllExceptions())
{
yield return innerEx;
}
}
}
यह आवर्ती सभी अपवादों ( AggregateException
एस के मामले सहित ) के माध्यम से जाता Message
है, उनमें निहित सभी संपत्ति को प्रिंट करने के लिए, लाइन ब्रेक द्वारा सीमांकित।
उदाहरण के लिए
var outerAggrEx = new AggregateException(
"Outer aggr ex occurred.",
new AggregateException("Inner aggr ex.", new FormatException("Number isn't in correct format.")),
new IOException("Unauthorized file access.", new SecurityException("Not administrator.")));
Console.WriteLine(outerAggrEx.ToFormattedString());
बाहरी aggr पूर्व हुआ।
इनर एग्री।
नंबर सही प्रारूप में नहीं है।
अनधिकृत फ़ाइल का उपयोग।
प्रशासक नहीं।
आपको अधिक विवरण के लिए अन्य अपवाद गुणों को सुनने की आवश्यकता होगी । उदाहरण के लिए Data
कुछ जानकारी होगी। तुम यह कर सकते थे:
foreach (DictionaryEntry kvp in exception.Data)
सभी व्युत्पन्न गुण पाने के लिए (आधार Exception
वर्ग पर नहीं ), आप कर सकते हैं:
exception
.GetType()
.GetProperties()
.Where(p => p.CanRead)
.Where(p => p.GetMethod.GetBaseDefinition().DeclaringType != typeof(Exception));