我正在使用 GraalVM 执行 JavaScript 文件,但在异常处理方面遇到问题。我的 JS 代码会回调 Java,如果这些 Java 方法之一抛出异常,那么我就会丢失原因链。
public class Example {
public static void doSomething() {
throw new RuntimeException("Example", new RuntimeException("Some nested exception"));
}
}
// --------------
var Example = Java.type("ex.Example");
function f() {
Example.doSomething();
}
// -------------
String src = ...
Source s = Source.newBuilder("js", src, "example").build();
try {
context.eval(s);
} catch (PolyglotException e) {
e.printStackTrace(); // This only prints the PolyglotException with the message "Example"
}
发生这种情况的原因是因为 Graal/Truffle 创建了一个 HostException 实例,该实例有一个不调用 super(e) 的构造函数,它将其分配给一个用于获取消息的内部字段,而不是其他任何内容。这似乎是故意的,但我不明白原因。这是安全问题吗?你能想出一种方法来改变我的这种行为吗?我非常希望在我的日志中找到异常的完整原因,但目前它停在 HostException
处,它通常只显示类似“A
”的内容(例如,如果错误的原始原因是 NoSuchElementException("A")
)
final class HostException extends RuntimeException implements TruffleException {
private final Throwable original;
HostException(Throwable original) {
this.original = original;
}
Throwable getOriginal() {
return original;
}
@Override
public String getMessage() {
return getOriginal().getMessage();
}
@Override
public synchronized Throwable fillInStackTrace() {
return this;
}
public Node getLocation() {
return null;
}
public boolean isCancelled() {
return getOriginal() instanceof InterruptedException;
}
}
最佳答案
我也遇到过同样的问题,结果发现,JS Error 具有以下功能:
printStackTrace: [Function],
fillInStackTrace: [Function],
getCause: [Function],
initCause: [Function],
toString: [Function],
getMessage: [Function],
getLocalizedMessage: [Function],
getStackTrace: [Function],
setStackTrace: [Function],
addSuppressed: [Function],
getSuppressed: [Function]
printStackTrace
,例如,打印 java 堆栈跟踪:
try {
Java.type('ClassWithException').throwRuntimeEx();
} catch (e) {
console.log(e.printStackTrace())
}
给出以下内容:
java.lang.RuntimeException: Example message
at ex.ClassWithException.throwRuntimeEx(ClassWithException.java:6)
at com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase.invokeHandle(HostMethodDesc.java:269)
at com.oracle.truffle.polyglot.HostMethodDesc$SingleMethod$MHBase.invoke(HostMethodDesc.java:261)
at com.oracle.truffle.polyglot.HostExecuteNode$1.executeImpl(HostExecuteNode.java:776)
at com.oracle.truffle.polyglot.GuestToHostRootNode.execute(GuestToHostRootNode.java:87)
at org.graalvm.compiler.truffle.runtime.OptimizedCallTarget.callProxy(OptimizedCallTarget.java:328)
...
at com.oracle.truffle.polyglot.PolyglotValue$InteropValue.execute(PolyglotValue.java:2008)
at org.graalvm.polyglot.Value.execute(Value.java:338)
at com.oracle.truffle.trufflenode.GraalJSAccess.isolateEnterPolyglotEngine(GraalJSAccess.java:2629)
Caused by: java.lang.RuntimeException: Inner exception
... 245 more
关于java - GraalVM 中的异常链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55953882/