如何在詹金斯管道中抛出异常?

How to throw exception in jenkins pipeline?

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

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new java.io.IOException java.lang.String

我检查了 scriptApproval 部分,没有待批准。

如果你想在异常时中止你的程序,你可以使用管道步骤 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. 
}

这就是我在 Jenkins 中的做法 2.x。

注意:不要使用错误信号,它会跳过任何 post 步骤。

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

似乎除了Exception之外没有其他类型的异常可以抛出。没有IOException,没有RuntimeException,等等

这会起作用:

throw new Exception("Something went wrong!")

但这些不会:

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

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

我可以让它以这样的 ABORTED 状态退出:

node('mynode') {

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

不过,将 currentBuild.result 设置为 'SUCCESS' 时同样不起作用。为此,您需要一个带有标志的 try-catch,就像 Pom12 的答案一样。