11namespace Spectre . Console ;
22
33// ExceptionFormatter relies heavily on reflection of types unknown until runtime.
4- // We'll suppress these warnings, but alert the user this method is not supported.
54[ UnconditionalSuppressMessage ( "AssemblyLoadTrimming" , "IL2026:RequiresUnreferencedCode" ) ]
65[ UnconditionalSuppressMessage ( "AssemblyLoadTrimming" , "IL2070:RequiresUnreferencedCode" ) ]
76[ UnconditionalSuppressMessage ( "AssemblyLoadTrimming" , "IL2075:RequiresUnreferencedCode" ) ]
8- [ RequiresDynamicCode ( AotWarning ) ]
97internal static class ExceptionFormatter
108{
119 public const string AotWarning = "ExceptionFormatter is currently not supported for AOT." ;
@@ -27,13 +25,6 @@ private static IRenderable GetException(Exception exception, ExceptionSettings s
2725 throw new ArgumentNullException ( nameof ( exception ) ) ;
2826 }
2927
30- // fallback to default ToString() if someone in an AOT is insisting on using this method
31- var stackTrace = new StackTrace ( exception , fNeedFileInfo : false ) ;
32- if ( stackTrace . GetFrame ( 0 ) ? . GetMethod ( ) is null )
33- {
34- return new Text ( exception . ToString ( ) ) ;
35- }
36-
3728 return new Rows ( GetMessage ( exception , settings ) , GetStackFrames ( exception , settings ) ) . Expand ( ) ;
3829 }
3930
@@ -71,8 +62,16 @@ private static Grid GetStackFrames(Exception ex, ExceptionSettings settings)
7162 }
7263
7364 var stackTrace = new StackTrace ( ex , fNeedFileInfo : true ) ;
74- var frames = stackTrace
75- . GetFrames ( )
65+ var allFrames = stackTrace . GetFrames ( ) ;
66+ if ( allFrames [ 0 ] ? . GetMethod ( ) == null )
67+ {
68+ // if we can't easily get the method for the frame, then we are in AOT
69+ // fallback to using ToString method of each frame.
70+ WriteAotFrames ( grid , stackTrace . GetFrames ( ) , styles ) ;
71+ return grid ;
72+ }
73+
74+ var frames = allFrames
7675 . FilterStackFrames ( )
7776 . ToList ( ) ;
7877
@@ -133,6 +132,18 @@ private static Grid GetStackFrames(Exception ex, ExceptionSettings settings)
133132 return grid ;
134133 }
135134
135+ private static void WriteAotFrames ( Grid grid , StackFrame [ ] frames , ExceptionStyle styles )
136+ {
137+ foreach ( var stackFrame in frames )
138+ {
139+ var s = stackFrame . ToString ( ) ;
140+ s = s . Replace ( " in file:line:column <filename unknown>:0:0" , string . Empty ) . TrimEnd ( ) ;
141+ grid . AddRow (
142+ $ "[{ styles . Dimmed . ToMarkup ( ) } ]at[/]",
143+ s . EscapeMarkup ( ) ) ;
144+ }
145+ }
146+
136147 private static void AppendParameters ( StringBuilder builder , MethodBase ? method , ExceptionSettings settings )
137148 {
138149 var typeColor = settings . Style . ParameterType . ToMarkup ( ) ;
0 commit comments