gpt4 book ai didi

grails - 如何检查 groovy 脚本是否存在编译错误

转载 作者:行者123 更新时间:2023-12-02 03:31:56 25 4
gpt4 key购买 nike

我们可以使用下面的代码在运行时创建并运行 groovyscript

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;

import java.io.File;
import java.io.IOException;

// Create a String with Groovy code.
final StringBuilder groovyScript = new StringBuilder();
groovyScript.append("class Sample {");
groovyScript.append(" String sayIt() { return \"Groovy says: Cool jajaja\" }");
groovyScript.append("}");



GroovyClassLoader gcl = new GroovyClassLoader()

GroovyCodeSource codeSource = new GroovyCodeSource(groovyScript.toString(), "aa", GroovyShell.DEFAULT_CODE_BASE)

//GCL will check for enabled cache over code source and use sourceCache to cache code with name
def scriptClass = gcl.parseClass(codeSource)
def classInstance = scriptClass.newInstance()

assert "Groovy says: Cool jajaja".equals(classInstance.sayIt())

现在假设在上面的代码中,我们引入了一个错误,现在上面的代码如下:

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;

import java.io.File;
import java.io.IOException;

// Create a String with Groovy code.
final StringBuilder groovyScript = new StringBuilder();
groovyScript.append("class Sample {");
groovyScript.append("jajaja");
groovyScript.append(" String sayIt() { return \"Groovy says: Cool jajaja\" }");
groovyScript.append("}");

GroovyClassLoader gcl = new GroovyClassLoader()

GroovyCodeSource codeSource = new GroovyCodeSource(groovyScript.toString(), "aa", GroovyShell.DEFAULT_CODE_BASE)

//GCL will check for enabled cache over code source and use sourceCache to cache code with name
def scriptClass = gcl.parseClass(codeSource)
def classInstance = scriptClass.newInstance()

assert "Groovy says: Cool jajaja".equals(classInstance.sayIt())

注意,我们在类声明之后的脚本中添加了“jajaja”。

这里应该做什么才能知道我们的脚本存在编译错误并且会因 MissingPropertyException 或其他异常而失败。

当尝试与 groovyConsole 相同时,它会破坏脚本并出现以下错误

1 compilation error:

unexpected token: jajaja at line: 1, column: 15

我们可以在运行脚本之前测试脚本是否有编译错误吗?对于此代码,添加 try catch block 对我来说不起作用。

最佳答案

GroovyShell 通过使用 try-catch block 可以很好地工作。

                  GroovyCodeSource codeSource = new GroovyCodeSource(script, "aa", GroovyShell.DEFAULT_CODE_BASE)

//GCL will check for enabled cache over code source and use sourceCache to cache code with name
def scriptClass
try {
def shell = new GroovyShell()
def data = shell.parse(codeSource.scriptText)
data.run()
}catch (Throwable e){
status = false
}
if(!status){
return "domain.script.compilation.errors"
}else{
return true
}

尽管一个后备方案是,每当您有一个不完整的脚本代码时,其余的代码都会稍后从其他脚本添加。此代码将失败,但这是开发人员问题而不是技术问题。

此外,这将运行脚本,这可能会导致数据更新,这是不好的。

关于grails - 如何检查 groovy 脚本是否存在编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32116233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com