我有一个Groovy脚本用来推广代码。长话短说,在该脚本的某个时间点,我知道它是否成功。如果不成功,我想使构建失败。在Groovy中是否有一种方法可以使构建失败?
示例:
在“执行Groovy脚本”插件中,您可以编写代码。
(插入API调用以推广代码)
if(checkPromote()){
//在此处使构建失败
}
其中'checkPromote'根据推广的状态返回true或false值。
我有一个Groovy脚本用来推广代码。长话短说,在该脚本的某个时间点,我知道它是否成功。如果不成功,我想使构建失败。在Groovy中是否有一种方法可以使构建失败?
示例:
在“执行Groovy脚本”插件中,您可以编写代码。
(插入API调用以推广代码)
if(checkPromote()){
//在此处使构建失败
}
其中'checkPromote'根据推广的状态返回true或false值。
在我看来,中止程序最优雅的方式是使用断言。
assert condition : "由于...构建失败"
声明式流水线DSL具有错误步骤:
error('Failing build because...')
请查看https://jenkins.io/doc/pipeline/steps/workflow-basic-steps,并搜索“Error signal”。
这样也可以:
sh "exit 1"
import hudson.AbortException
//other code
throw new AbortException("Error message .")
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new hudson.AbortException
。 - acm在Jenkins世界中有不同类型的"Groovy脚本",每种类型的解决方案都不相同。
"Execute Groovy script" plugin (a plain Groovy script which runs on a node)
System.exit(1)
// NOTE: Don't use it in System Groovy Script, Groovy Postbuild, Scriptler or Pipeline
// because it runs on master and terminates the Jenkins server process!
System Groovy Script / Groovy Postbuild / Scriptler (runs on master):
import hudson.model.*;
def currentBuild = Thread.currentThread().executable
currentBuild.result = Result.FAILURE
This works only for "System Groovy Script"
return 1
Pipeline:
currentBuild.result = 'FAILURE'// one way
error("Error Message") // another way
当然,还有更多的人工方法,比如抛出异常、执行错误命令、调用不存在的函数或使用错误的参数等等。
通常我使用像 throw new Exception("错误信息")
这样简单的语句,你可以尝试一下:
if(checkPromote()){
throw new Exception("Error Message")
}
你应该使用
currentBuild.result = 'FAILURE'
return false
。 - Eddie