Fix IndexOutOfRangeException

Fix `IndexOutOfRangeException` if an exception does not have an associated stack trace.

Resolves #1798.
This commit is contained in:
martincostello 2025-04-09 11:32:16 +01:00 committed by Patrik Svensson
parent b5c839030c
commit 6105ee2a86
2 changed files with 18 additions and 1 deletions

View File

@ -65,7 +65,7 @@ internal static class ExceptionFormatter
var stackTrace = new StackTrace(ex, fNeedFileInfo: true);
var allFrames = stackTrace.GetFrames();
if (allFrames[0]?.GetMethod() == null)
if (allFrames.Length > 0 && allFrames[0]?.GetMethod() == null)
{
// if we can't easily get the method for the frame, then we are in AOT
// fallback to using ToString method of each frame.

View File

@ -142,4 +142,21 @@ public partial class AnsiConsoleTests
.ShouldBe("Hello\nWorld\n");
}
}
public sealed class WriteException
{
[Fact]
public void Should_Not_Throw_If_Exception_Has_No_StackTrace()
{
// Given
var console = new TestConsole();
var exception = new InvalidOperationException("An exception.");
// When
void When() => console.WriteException(exception);
// Then
Should.NotThrow(When);
}
}
}