1

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

JavaScript中是否有一些函数可以退出脚本?

4

2 回答 2

2

不,没有。但是您可以创建一个异常,例如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);
}
于 2011-06-17T01:16:51.110 回答
1

这是一个想法:

将您的脚本包装在一个函数中并调用它。从该函数返回将退出您的脚本。

//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
}
于 2011-10-19T15:49:50.083 回答