How to throw exception in jenkins pipeline?

允我心安 提交于 2020-01-12 12:09:20

问题


I have handled the Jenkins pipeline steps with try catch blocks. I want to throw an exception manually for some cases. but it shows the below error.

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

I checked the scriptApproval section and there is no pending approvals.


回答1:


If you want to abort your program on exception, you can use pipeline step error to stop the pipeline execution with an error. Example :

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

   error "Program failed, please read logs..."
}

If you want to stop your pipeline with a success status, you probably want to have some kind of boolean indicating that your pipeline has to be stopped, e.g:

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



回答2:


It seems no other type of exception than Exception can be thrown. No IOException, no RuntimeException, etc.

This will work:

throw new Exception("Something went wrong!")

But these won't:

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



回答3:


This is how I do it in Jenkins 2.x.

Notes: Do not use the error signal, it will skip any post steps.

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


来源:https://stackoverflow.com/questions/42718785/how-to-throw-exception-in-jenkins-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!