如何在Jenkins Pipeline中抛出异常?

54

我已经使用try catch块处理了Jenkins流水线步骤。 我想在某些情况下手动抛出异常,但它显示以下错误。

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new java.io.IOException java.lang.String
我检查了scriptApproval部分,没有待批准的内容。
5个回答

66

如果您希望在出现异常时中止程序,可以使用管道步骤 error 以错误状态停止管道执行。示例:

try {
  // Some pipeline code
} catch(Exception e) {
   // Do something with the exception 

   error "Program failed, please read logs..."
}
如果您想以成功的状态停止流水线,则可能需要一些布尔值,指示必须停止您的流水线,例如:

如果你想要使用成功状态来停止你的pipeline,你可能需要一个布尔变量来指示必须停止pipeline,例如:

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. 
}

我不想因为失败状态而中止我的流水线。我想用成功状态来中止我的流水线,所以我希望能够在catch块中处理throw选项来实现这一点。是否可能用成功状态中止流水线? - Yahwe Raj
我已经相应地编辑了我的帖子。如果这不是您要寻找的,请在您的初始问题中提供更多细节,例如代码示例。 - Pom12
没错,我在我的代码中也用了同样的解决方案 :-) - Yahwe Raj
2
使用“错误”步骤并不总是理想的,因为它会跳过管道的其余部分。这相当于在Python中使用sys.exit()或在Node中使用process.exit() - Marco Roy
之前因为某些错误而失败的阶段是否可以重试?! - Prathamesh dhanawade
1
@Prathameshdhanawade 请查看重试块的Jenkinsfile示例。(有趣的事实:此Gist的评论链接到这个问题。) - Gerold Broser

30

以下是我在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"
                    }
                }
            }            
        }

7
应该接受这个答案。似乎除了 Exception 之外,没有其他类型的异常可以被抛出。没有 IOException,没有 RuntimeException 等。 - Marco Roy
6
请注意,至少在当前版本中,即使您使用error()失败,后续步骤仍然会执行。 - Raúl Salinas-Monteagudo
在这里设置 currentBuild.result = "SUCCESS" 对我来说不起作用;它仍然会进入 post.failure 块。 - Christopher Rung
throw new Exception 对我不起作用,构造函数似乎不存在于一个字符串参数为1的情况下:groovy.lang.MissingMethodException: No signature of method: java.lang.Exception.call() is applicable for argument types: : (org.codehaus.groovy.runtime.GStringImpl) - jaques-sam
那是因为我从一个类内抛出了异常。Groovy 太蠢了,为什么不能知道一个类内的所有类型... - jaques-sam
如果这个情况不再成立,我建议在答案中添加一条注释,否则会误导人。 - felipecrs

19

似乎没有任何类型的异常可以被抛出,除了Exception。没有IOException,没有RuntimeException等。

这样做可以:

throw new Exception("Something went wrong!")

但这些不会:

throw new IOException("Something went wrong!")
throw new RuntimeException("Something went wrong!")

3
如果您从权限面板中批准,确实可以使用IOException(String)。但这是否有用是一个不同的问题。 - Raúl Salinas-Monteagudo
2
这在以前对我来说是有效的,但最近我一直收到 org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new java.lang.Exception 的错误信息。 - cowlinator
如果不允许使用,请前往Jenkins配置页面的“in-process script approval”(脚本批准)部分进行批准。链接为https://www.jenkins.io/doc/book/managing/script-approval/。 - Bartek K

1

我可以像这样使其以ABORTED状态退出:

node('mynode') {

    stage('Some stage') {
    
        currentBuild.result = 'ABORTED'
        error('Quitting')
    }
}

但是,当将currentBuild.result设置为“SUCCESS”时,同样的方法不起作用。为了解决这个问题,您需要使用类似Pom12答案中的try-catch标志。


1
我使用了.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的值,您可以设计后构建操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接