如何在jenkins管道中抛出异常?

Yah*_*Raj 16 jenkins jenkins-plugins jenkins-pipeline

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

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new java.io.IOException java.lang.String
Run Code Online (Sandbox Code Playgroud)

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

Pom*_*m12 28

如果要在异常时中止程序,可以使用管道步骤error来停止管道执行并显示错误.示例:

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

   error "Program failed, please read logs..."
}
Run Code Online (Sandbox Code Playgroud)

如果要以成功状态停止管道,可能需要某种布尔值来指示必须停止管道,例如:

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. 
}
Run Code Online (Sandbox Code Playgroud)

  • 使用“error”步骤并不总是理想的,因为它会跳过管道的其余部分。它相当于在 python 中使用“sys.exit()”,或者在 Node 中使用“process.exit()”。 (2认同)

Lea*_*ner 8

这就是我在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"
                    }
                }
            }            
        }
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案。看来除了`Exception`之外没有其他类型的异常可以抛出。没有`IOException`,没有`RuntimeException`等。 (4认同)
  • 请注意,至少在当前版本中,即使您因 error() 失败,后置步骤也会确实执行。 (3认同)

Mar*_*Roy 7

似乎没有其他异常Exception可以抛出。不IOException,不RuntimeException,等等。

这将起作用:

throw new Exception("Something went wrong!")
Run Code Online (Sandbox Code Playgroud)

但是这些不会:

throw new IOException("Something went wrong!")
throw new RuntimeException("Something went wrong!")
Run Code Online (Sandbox Code Playgroud)

  • 如果您从权限面板批准它,您确实可以使用 IOException(String)。这是否有用是另一个问题。 (2认同)
  • 这曾经对我有用,但最近我得到了`org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException:不允许脚本使用新的java.lang.Exception` (2认同)