我使用try catch块处理了Jenkins管道步骤。我想在某些情况下手动抛出异常。但它显示以下错误。
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new java.io.IOException java.lang.String
我查看了scriptApproval部分,并且没有待批准。
答案 0 :(得分:21)
如果要在异常时中止程序,可以使用管道步骤error
来阻止管道执行并出现错误。示例:
try {
// Some pipeline code
} catch(Exception e) {
// Do something with the exception
error "Program failed, please read logs..."
}
如果你想以成功状态停止你的管道,你可能想要某种布尔值,表明你的管道必须停止,例如:
boolean continuePipeline = true
try {
// Some pipeline code
} catch(Exception e) {
// Do something with the exception
continuePipeline = false
currentBuild.result = 'SUCCESS'
}
if(continuePipeline) {
// The normal end of your pipeline if exception is not caught.
}
答案 1 :(得分:2)
这就是我在Jenkins 2.x中的做法。
注意:不要使用错误信号,它会跳过任何发布步骤。
stage('stage name') {
steps {
script {
def status = someFunc()
if (status != 0) {
// Use SUCCESS FAILURE or ABORTED
currentBuild.result = "FAILURE"
throw new Exception("Throw to stop pipeline")
// do not use the following, as it does not trigger post steps (i.e. the failure step)
// error "your reason here"
}
}
}
post {
success {
script {
echo "success"
}
}
failure {
script {
echo "failure"
}
}
}
}
答案 2 :(得分:1)
似乎无法抛出Exception
以外的其他类型的异常。没有IOException
,没有RuntimeException
等
这将起作用:
throw new Exception("Something went wrong!")
但是这些不会:
throw new IOException("Something went wrong!")
throw new RuntimeException("Something went wrong!")
答案 3 :(得分:0)
我使用了.jenkinsfile。 我是通过以下方式完成的:
stage('sample') {
steps {
script{
try{
bat '''sample.cmd'''
RUN_SAMPLE_RESULT="SUCCESS"
echo "Intermediate build result: ${currentBuild.result}"
}//try
catch(e){
RUN_SAMPLE_RESULT="FAILURE"
echo "Intermediate build result: ${currentBuild.result}"
// normal error handling
throw e
}//catch
}//script
}//steps
}//stage
基于RUN_SAMPLE_RESULT值,您可以设计生成后的操作。