1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . Text ;
4+ using YamlDotNet . Core ;
5+
6+ namespace Synapse . Core . Utilities
7+ {
8+ public class ExceptionHelpers
9+ {
10+ public static string UnwindException ( Exception ex )
11+ {
12+ return UnwindException ( null , ex ) ;
13+ }
14+ public static string UnwindException ( string context , Exception ex , bool asSingleLine = false )
15+ {
16+ string lineEnd = asSingleLine ? "|" : @"\r\n" ;
17+
18+ StringBuilder msg = new StringBuilder ( ) ;
19+ if ( ! string . IsNullOrWhiteSpace ( context ) )
20+ msg . Append ( $ "An error occurred in: { context } { lineEnd } " ) ;
21+
22+ msg . Append ( $ "{ ex . Message } { lineEnd } " ) ;
23+
24+ if ( ex . InnerException != null )
25+ {
26+ if ( ex . InnerException is AggregateException )
27+ {
28+ AggregateException ae = ex . InnerException as AggregateException ;
29+ foreach ( Exception wcx in ae . InnerExceptions )
30+ {
31+ Stack < Exception > exceptions = new Stack < Exception > ( ) ;
32+ exceptions . Push ( wcx ) ;
33+
34+ while ( exceptions . Count > 0 )
35+ {
36+ Exception e = exceptions . Pop ( ) ;
37+
38+ if ( e . InnerException != null )
39+ exceptions . Push ( e . InnerException ) ;
40+
41+ msg . Append ( $ "{ e . Message } { lineEnd } " ) ;
42+ }
43+ }
44+ }
45+ else
46+ {
47+ Stack < Exception > exceptions = new Stack < Exception > ( ) ;
48+ exceptions . Push ( ex . InnerException ) ;
49+
50+ while ( exceptions . Count > 0 )
51+ {
52+ Exception e = exceptions . Pop ( ) ;
53+
54+ if ( e . InnerException != null )
55+ exceptions . Push ( e . InnerException ) ;
56+
57+ msg . Append ( $ "{ e . Message } { lineEnd } " ) ;
58+ }
59+ }
60+ }
61+
62+ return asSingleLine ? msg . ToString ( ) . TrimEnd ( '|' ) : msg . ToString ( ) ;
63+ }
64+ }
65+
66+
67+
68+
69+ public static class ExceptionExtensions
70+ {
71+ public static Exception ToFriendlyYamlException ( this Exception ex , string message = null , string yaml = null )
72+ {
73+ if ( ex is YamlException yx )
74+ {
75+ string err = null ;
76+ if ( ! string . IsNullOrWhiteSpace ( yaml ) )
77+ err = $ "\r \n Text of range is: { yaml . Substring ( yx . Start . Index , yx . End . Index - yx . Start . Index ) } ";
78+
79+ string msg = $ "Error encountered with YAML between line { yx . Start . Line } /ch { yx . Start . Column } and line { yx . End . Line } /ch { yx . End . Column } , and between document indexes { yx . Start . Index } and { yx . End . Index } .{ err } \r \n { message } ";
80+
81+ return new Exception ( message : msg , innerException : yx ) ;
82+ }
83+ else
84+ return ex ;
85+ }
86+ }
87+ }
0 commit comments