如何获取 Rhino 中当前的脚本名称和行号?
我正在使用 Java 和 Mozilla Rhino 创建一个游戏引擎,我希望所有错误都调用一个函数并为其提供错误消息,例如
...
} catch(Exception e) {
Abort(e);
}
...
public void Abort(str) {
System.out.println("Script error in "current_script_name+" line: "+line_number\n\n"+e);
}
This is easy for RhinoException,但我希望其他人也有同样的事情,例如 IOException。
I am creating a game engine using Java and Mozilla Rhino, and I want all errors to call one function and provide it with the error message, like
...
} catch(Exception e) {
Abort(e);
}
...
public void Abort(str) {
System.out.println("Script error in "current_script_name+" line: "+line_number\n\n"+e);
}
This is easy for RhinoException, but I want to have the same thing for others, like IOException.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这在某种程度上取决于异常是如何抛出的,所以我需要猜测。这取决于您用来执行 Rhino 的优化级别。
我猜测本机 Java 代码会抛出异常(即,您没有使用 throw new Packages.java.io.IOException("...") )。在这种情况下,您可以使用 printStackTrace() 来弄清楚。这是一个小脚本(名为
test.jsh.js
,您将在堆栈跟踪中看到它),您可以在 Rhino shell 中运行:... 及其输出:
如果您确实想使用上面的
Abort()
函数,您可以从上面的堆栈跟踪中解析相应的行;或者,您可以显示整个堆栈跟踪,这可能会更有帮助,具体取决于您想要执行的操作。It depends a bit how the exceptions are being thrown, so I'll need to take a guess. And it depends on the optimization level you're using to execute Rhino.
I am guessing that exceptions are being thrown out of native Java code (i.e., you are not using
throw new Packages.java.io.IOException("...")
). In that case, you can use printStackTrace() to figure it out. Here's a little script (namedtest.jsh.js
, which you will see in the stack trace) you can run in the Rhino shell:... and its output:
If you really want to use exactly the
Abort()
function you have above, you can parse the appropriate line out of the stack trace above; alternatively, you can display the whole stack trace, which may be more helpful, depending what you want to do.为什么不为异常设置某种日志记录功能(例如 Log4j)?这样,您可以设置一个
properties
文件,这样每次您记录某些内容时,它都会以相同的方式输出(而不是总是调用Abort()
函数。此外,Log4j支持获取行号和其他功能: Log4j模式。Why don't you setup some kind of logging feature for your exceptions like Log4j? With this, you can set a
properties
file, that way every time you log something it outputs the same way (instead of always calling anAbort()
function. Also, Log4j supports getting line numbers and other features: Log4j Patterns.