3

I'm writing a library that parses text files that are not written in Java. When I encounter a syntax error in these text files, I would like to construct a clickable stack trace with the relevant file name and line number of these files. I already have an exception with this information in the exception name, but not the stack trace.

Ideally, my code would look something like this:

try {

   // Try to parse the file
} catch (MySyntaxException e) {
    StackTraceElement[] stackTrace = e.getStackTrace();
    StackTraceElement[] newStackTrace = new StackTraceElement[stackTrace.length+1];
    newStackTrace[0] = new StackTraceElement(e.getClassNameEquivalent(), "", e.getFile(), e.getLineNumber());
    System.arraycopy(stackTrace, 0, newStackTrace, 1, stackTrace.length);
    e.setStackTrace(newStackTrace);
    throw e;
}

When I do this, I get a stack trace that looks something like this:

org.example.MySyntaxException: Something went wrong
    at Filename.yaml.(config/files/Filename.yaml:21)
    at org.example.MyParser.parse(MyParser.java:41)
    // ...

However, IntelliJ doesn't treat the line Filename.yaml.(config/files/Filename.yaml:21) as clickable. Is there some way to convince IDEs that I can click this line?

Johannes Brodwall
  • 7,673
  • 5
  • 34
  • 28
  • try providing absolute path. I am not sure that would work but doesn't hurt giving it a shot. – ringadingding Mar 01 '19 at 21:10
  • This most-likely depends on how the IDE displays stacktraces, as elements in a stacktrace that are displayed in a Unix terminal (or Windows CMD) aren't clickable. For that reason, I feel that answers will differ between IDEs, as IntelliJ or Eclipse might require a custom plugin for this to work. – Jacob G. Mar 01 '19 at 21:30
  • I ran into a similar problem, it seems that _not_ providing a class name forces IntelliJ to lookup the file path correctly. i.e. instead of `new StackTraceElement(e.getClassNameEquivalent(), "", e.getFile(), e.getLineNumber());` try `new StackTraceElement("", "", e.getFile(), e.getLineNumber());`. – Y.H. Sep 01 '22 at 18:45

0 Answers0