-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathExceptionExtensions.cs
More file actions
112 lines (101 loc) · 5.98 KB
/
ExceptionExtensions.cs
File metadata and controls
112 lines (101 loc) · 5.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
using System;
using System.Collections.Generic;
using System.Text;
namespace Platform.Exceptions
{
/// <summary>
/// <para>Provides a set of extension methods for <see cref="Exception"/> objects.</para>
/// <para>Предоставляет набор методов расширения для объектов <see cref="Exception"/>.</para>
/// </summary>
public static class ExceptionExtensions
{
/// <summary>
/// <para>Represents the separator used within the process of generating a representation string (<see cref="ToStringWithAllInnerExceptions(Exception)"/>) to separate different inner exceptions from each other. This field is constant.</para>
/// <para>Представляет разделитель, используемый внутри процесса формирования строки-представления (<see cref="ToStringWithAllInnerExceptions(Exception)"/>) для разделения различных внутренних исключений друг от друга. Это поле является константой.</para>
/// </summary>
public static readonly string ExceptionContentsSeparator = "---";
/// <summary>
/// <para>Represents a string returned from <see cref="ToStringWithAllInnerExceptions(Exception)"/> in the event of an unsuccessful attempt to format an exception. This field is a constant.</para>
/// <para>Представляет строку выдаваемую из <see cref="ToStringWithAllInnerExceptions(Exception)"/> в случае неудачной попытки форматирования исключения. Это поле является константой.</para>
/// </summary>
public static readonly string ExceptionStringBuildingFailed = "Unable to format exception.";
/// <summary>
/// <para>Ignores the exception, notifying the <see cref = "IgnoredExceptions" /> class about it.</para>
/// <para>Игнорирует исключение, уведомляя об этом класс <see cref="IgnoredExceptions"/>.</para>
/// </summary>
/// <param name="exception"><para></para><para></para></param>
public static void Ignore(this Exception exception) => IgnoredExceptions.RaiseExceptionIgnoredEvent(exception);
/// <summary>
/// <para>Returns a string that represents the specified exception with all its inner exceptions.</para>
/// <para>Возвращает строку, которая представляет указанное исключение со всеми его внутренними исключениями.</para>
/// </summary>
/// <param name="exception"><para>The exception that will be represented as a string.</para><para>Исключение, которое будет представленно в виде строки.</para></param>
/// <returns><para>A string that represents the specified exception with all its inner exceptions.</para><para>Cтроку, которая представляет указанное исключение со всеми его внутренними исключениями.</para></returns>
public static string ToStringWithAllInnerExceptions(this Exception exception)
{
try
{
var sb = new StringBuilder();
sb.BuildExceptionString(exception, 0);
return sb.ToString();
}
catch (Exception ex)
{
ex.Ignore();
return ExceptionStringBuildingFailed;
}
}
private static void BuildExceptionString(this StringBuilder sb, Exception exception, int level)
{
// Iterative implementation without recursion to avoid stack overflow issues
var current = exception;
var currentLevel = level;
while (current != null)
{
// Step 1: Message with indent
sb.Indent(currentLevel);
sb.AppendLine(current.Message);
// Step 2: Separator with indent
sb.Indent(currentLevel);
sb.AppendLine(ExceptionContentsSeparator);
// Step 3: Check for inner exception
if (current.InnerException != null)
{
sb.Indent(currentLevel);
sb.AppendLine("Inner exception: ");
// Move to inner exception for next iteration
current = current.InnerException;
currentLevel++;
}
else
{
// Step 4: Final separator for innermost
sb.Indent(currentLevel);
sb.AppendLine(ExceptionContentsSeparator);
// Step 5: Stack trace for innermost
sb.Indent(currentLevel);
sb.AppendLine(current.StackTrace);
break;
}
}
// Now we need to add the trailing separators and stack traces for all outer exceptions
// Working backwards from the chain
var exceptions = new List<Exception>();
current = exception;
while (current != null)
{
exceptions.Add(current);
current = current.InnerException;
}
// Add the closing parts for each exception (except the innermost which we already handled)
for (int i = exceptions.Count - 2; i >= 0; i--)
{
sb.Indent(level + i);
sb.AppendLine(ExceptionContentsSeparator);
sb.Indent(level + i);
sb.AppendLine(exceptions[i].StackTrace);
}
}
private static void Indent(this StringBuilder sb, int level) => sb.Append('\t', level);
}
}