Try-catch block in Jenkins pipeline script

后端 未结 5 1668
有刺的猬
有刺的猬 2020-12-13 18:16

I\'m trying to use the following code to execute builds, and in the end, execute post build actions when builds were successful. Still, I get a MultipleCompilationErrorsExce

相关标签:
5条回答
  • 2020-12-13 18:53

    Look up the AbortException class for Jenkins. You should be able to use the methods to get back simple messages or stack traces. In a simple case, when making a call in a script block (as others have indicated), you can call getMessage() to get the string to echo to the user. Example:

    script {
            try {
                sh "sudo docker rmi frontend-test"
            } catch (err) {
                echo err.getMessage()
                echo "Error detected, but we will continue."
            }
            ...continue with other code...
    }
    
    0 讨论(0)
  • 2020-12-13 18:54

    This answer worked for me:

    pipeline {
      agent any
      stages {
        stage("Run unit tests"){
          steps {
            script {
              try {
                sh  '''
                  # Run unit tests without capturing stdout or logs, generates cobetura reports
                  cd ./python
                  nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
                  cd ..
                  '''
              } finally {
                junit 'nosetests.xml'
              }
            }
          }
        }
        stage ('Speak') {
          steps{
            echo "Hello, CONDITIONAL"
          }
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-13 19:00

    You're using the declarative style of specifying your pipeline, so you must not use try/catch blocks (which are for Scripted Pipelines), but the post section. See: https://jenkins.io/doc/book/pipeline/syntax/#post-conditions

    0 讨论(0)
  • 2020-12-13 19:02

    try/catch is scripted syntax. So any time you are using declarative syntax to use something from scripted in general you can do so by enclosing the scripted syntax in the scripts block in a declarative pipeline. So your try/catch should go inside stage >steps >script.

    This holds true for any other scripted pipeline syntax you would like to use in a declarative pipeline as well.

    0 讨论(0)
  • 2020-12-13 19:10

    try like this (no pun intended btw)

    script {
      try {
          sh 'do your stuff'
      } catch (Exception e) {
          echo 'Exception occurred: ' + e.toString()
          sh 'Handle the exception!'
      }
    }
    

    The key is to put try...catch in a script block in declarative pipeline syntax. Then it will work. This might be useful if you want to say continue pipeline execution despite failure (eg: test failed, still you need reports..)

    0 讨论(0)
提交回复
热议问题