53

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.

Yahwe Raj
  • 1,947
  • 5
  • 25
  • 37

5 Answers5

65

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. 
}
Community
  • 1
  • 1
Pom12
  • 7,622
  • 5
  • 50
  • 69
  • I don't want to abort my pipeline with failure status. I want to abort my pipeline with success status, so I would like to handle the throw option to achieve this in the catch. Is it possible to abort the pipeline with success status? – Yahwe Raj Mar 11 '17 at 05:09
  • I edited my post accordingly. If that's not what you are looking for, please provide more details in your initial question, like code samples. – Pom12 Mar 13 '17 at 09:16
  • Exactly, I have done the same solution in my code:-) – Yahwe Raj Mar 13 '17 at 15:42
  • 2
    Using the `error` step is not always ideal, as it will skip the rest of the pipeline. It's the equivalent of using `sys.exit()` in python, or `process.exit()` in Node. – Marco Roy Feb 04 '19 at 23:06
  • Is it possible to RETRY the failed stage which failed earlier due to some error ?! – Prathamesh dhanawade Nov 11 '19 at 17:39
  • 1
    @Prathameshdhanawade See [Sample of Jenkinsfile for retry block.](https://gist.github.com/daipresents/c7f982ffce9c1bda73b4387d6b1ae3da#file-jenkinsfile). (Fun fact: a comment to this Gist links to exactly this question here.) – Gerold Broser Sep 17 '21 at 22:24
30

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"
                    }
                }
            }            
        }
Learner
  • 2,459
  • 4
  • 23
  • 39
  • 7
    This should be the accepted answer. It seems no other type of exception than `Exception` can be thrown. No `IOException`, no `RuntimeException`, etc. – Marco Roy Feb 04 '19 at 23:02
  • 6
    Note, at least in the current version, the post steps are executed indeed even if you fail with error(). – Raúl Salinas-Monteagudo Sep 12 '19 at 10:28
  • setting `currentBuild.result = "SUCCESS"` does not work for me here; it still drops into the `post.failure` block. – Christopher Rung Jan 21 '20 at 23:00
  • throw new Exception doesn't work for me, constructor does't seem to exist for 1 argument as string: `groovy.lang.MissingMethodException: No signature of method: java.lang.Exception.call() is applicable for argument types: : (org.codehaus.groovy.runtime.GStringImpl)` – jaques-sam Mar 02 '20 at 09:28
  • That's because I was throwing the exception from within a class. Groovy is so stupid, why can't it know all types within a class... – jaques-sam Mar 02 '20 at 10:06
  • If this isn't true any longer, I suggest to add a note in the answer, because otherwise it's misleading. – felipecrs Feb 25 '22 at 15:45
19

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!")
Marco Roy
  • 4,004
  • 7
  • 34
  • 50
  • 3
    You can use IOException(String) indeed if you approve it from the permission panel. Whether that's useful is a different question. – Raúl Salinas-Monteagudo Sep 12 '19 at 10:29
  • 2
    This used to work for me, but lately I have been getting `org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new java.lang.Exception` – cowlinator Nov 15 '19 at 02:34
  • for not permitter to use please go to jenkins configuration “in-process script approval” https://www.jenkins.io/doc/book/managing/script-approval/ and approve there – Bartek K Apr 12 '23 at 10:15
1

I used .jenkinsfile. I did it in the following way:

    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

Based on value of RUN_SAMPLE_RESULT you can design post build action.

np2807
  • 1,050
  • 15
  • 30
1

I'm able to get it to exit with an ABORTED status like this:

node('mynode') {

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

The same does not work when setting currentBuild.result to 'SUCCESS', though. For that, you need a try-catch with a flag like the answer from Pom12.

John Michelau
  • 1,001
  • 8
  • 12