我正在使用 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;
}
}