110 points · by laech · 3y ago · 21 comments
static void Main()
{
try
{
throw new DivideByZeroException("Boom!");
}
catch (Exception ex)
{
var trace = new StackTrace(ex, true);
var frame = trace.GetFrame(0);
var targetFilename = frame.GetFileName();
var targetLineNumber = frame.GetFileLineNumber();
Console.WriteLine($"Exception occurred at {targetFilename}, line {targetLineNumber}");
if (File.Exists(targetFilename))
{
var source = File.ReadAllLines(targetFilename);
var startIndex = Math.Max(0, targetLineNumber - 3);
var endIndex = Math.Min(source.Length - 1, targetLineNumber + 1);
for (var i = startIndex; i <= endIndex; i++)
{
var lineNumber = i + 1;
Console.WriteLine($"{(lineNumber == targetLineNumber ? $">> {lineNumber}" : $" {lineNumber}")}{source[i]}");
}
}
}
}https://github.com/bnorm/kotlin-power-assert/
You just add the Gradle plugin and you're done.
But I guess for such feature to be possible you'd have to pack the source code inside the jar itself.
https://docs.oracle.com/javase%2F9%2Fdocs%2Fapi%2F%2F/java/l...
Logback even supports including the call chain in the output, so you could include the parent method, grand parent method etc. This probably uses reflection, so it could have a negative impact for applications that need a high performance.
Some unsolicited opinion: One potential code pet peeve i always have is that the overloads being used in java serves no purpose, but makes the code super confusing to read without using an IDE.
For example, https://github.com/laech/java-stacksrc/blob/main/core/src/ma... , which is code to decorate the stacktrace element, calls the function `decorate`. However, there's several overloads, all named decorate! It is certainly a better naming convention to call it `decorateElement` imho.