嵌入Rhino时,如何从中返回退出代码

How do you return an exit code from Rhino when embedding it?

本文关键字:返回 退出 代码 Rhino 嵌入      更新时间:2023-09-26

我使用Java运行使用JRE捆绑的默认Rhino编写的JavaScript简单脚本。我希望能够在应用程序和命令行版本中使用相同的脚本,因此我不能使用java.lang.System.exit(3)(它会提前退出主机应用程序。)我不能使用安全管理器来阻止它,因为当安全管理器生效时,人们会抱怨性能问题。

JavaScript中是否有一些用于退出脚本的函数?

不,没有。但是您可以创建一个名为ExitError:的异常

public class ExitError extends Error {
    private final int code;
    public ExitError(int code) {
        this.code = code;
    }
    public int getCode() {
        return code;
    }
}

现在,在应用程序的脚本运行程序中,您可以执行以下操作:

public int runScript() {
    try {
        // Invoke script via Rhino
    } catch (ExitError exc) {
        return exc.getCode();
    }
}

在命令行版本中:

public static void main(String[] args) {
    try {
        // Invoke script via Rhino
    } catch (ExitError exc) {
        System.exit(exc.getCode());
    }
}

此外,在JS代码中,编写一个包装器函数:

function exit(code) {
    throw new ExitError(code);
}

这里有一个想法:

将脚本封装在函数中并调用它。从该函数返回将退出脚本。

//call main
main();
//The whole work is done in main
function main(){
  if(needToExit){
    //log error and return. It will essentially exit the script
    return;
  }
  //your script goes here
}