graaljs icon indicating copy to clipboard operation
graaljs copied to clipboard

Java stack trace missing some SourceSection data when throwing exceptions

Open wagyourtail opened this issue 3 years ago • 1 comments

When throwing a java exception, the stacktrace and exception appear to be missing some data. For example, running the following code:

public static void main(String[] args) {
        try {
            Context context = Context.newBuilder("js").allowAllAccess(true).build();
            context.eval(Source.newBuilder("js", new File("./test.js")).build());
        } catch (PolyglotException e) {
            e.printStackTrace();
            System.err.println(e.getSourceLocation());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

and in test.js

function test() {
    throw new (Java.type('java.lang.NullPointerException'))();
}
test();

creates this result

org.graalvm.polyglot.PolyglotException
	at <js> test(Unknown)
	at <js> :program(test.js:4:86-91)
	at org.graalvm.polyglot.Context.eval(Context.java:399)
	at xyz.wagyourtail.Test.main(Test.java:14)
Caused by host exception: java.lang.NullPointerException
null

while throwing a guest exception, ie, replacing the line in test.js with throw new Error(); results in

Error
	at <js> test(test.js:2:29-39)
	at <js> :program(test.js:4:46-51)
	at org.graalvm.polyglot.Context.eval(Context.java:399)
	at xyz.wagyourtail.Test.main(Test.java:14)
null

it's strange that the SourceSection is missing for the guest exception too... I don't think that's correct either, it's present in the e.getPolyglotStackTrace()'s first element, but not .getSourceLocation()

tested with 22.1.0

wagyourtail avatar May 14 '22 11:05 wagyourtail

Hi, Thank you for reporting this, we will take a look into it and get back to you

oubidar-Abderrahim avatar May 18 '22 15:05 oubidar-Abderrahim

it appears this issue may be fixed in a newer version. I just re-tested it with the tests above. while getSourceLocation() still seems to return null in both cases, the stack trace doesn't show Unknown. is that the expected behavoir of getSourceLocation()?

wagyourtail avatar Oct 26 '23 05:10 wagyourtail

I can confirm that this issue is already fixed, tested with 23.1:

org.graalvm.polyglot.PolyglotException
	at <js> test(test.js:2:22-79)
	at <js> :program(test.js:4:83-88)
	at org.graalvm.polyglot/org.graalvm.polyglot.Context.eval(Context.java:402)
	at Test.main(Test.java:8)
Caused by host exception: java.lang.NullPointerException
null

As for the source location, you can use PolyglotException.getPolyglotStackTrace(), and get the source location from the first StackFrame.

Currently, PolyglotException.getSourceLocation() only works when the source location is readily available where the exception is constructed and not when it requires a stack walk (as is the case for new Error). I agree this makes it not very useful. We could probably change this.

woess avatar Nov 02 '23 14:11 woess