How to throw exception in jenkins pipeline?

2020-07-01 17:26发布

问题:

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:

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


回答3:

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!")