Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 MultipleCompilationErrorsException, saying that my try block is Not a valid section definition. Please help, I tried a lot reorganize the block but can't seem to be able to solve the issue.

#!/usr/bin/env groovy

pipeline{

agent any 
    try {
        stages{
            stage("Parallel 1") {
                steps {
                    parallel (
                       'firstTask' : { 
                            build( "DSL-Controll-Demo-Fibonacci-1" )
                        },
                        'secondTask' : { 
                            build( "DSL-Controll-Demo-Fibonacci-2" )
                        }
                    )
                }
            }
            stage("Feature") {
                steps {
                        build( "DSL-Controll-Demo-Fibonacci-5" )
                        build( "DSL-Controll-Demo-Fibonacci-6" )
                }
            }
            stage("Parallel 2") {
                steps{
                    parallel (
                        "thirdTask" : { 
                            build( "DSL-Controll-Demo-Fibonacci-3" )
                        },
                        "forthTask" : { 
                            build( "DSL-Controll-Demo-Fibonacci-4" )
                        }
                    )
                }
            }
        }
    }   

    catch(all) {
        currentBuild.result = 'FAILURE'
    }   

    if(currentBuild.result != 'FAILURE') {
        stages{
            stage("Post Build") {
                steps {
                    build("DSL-Controll-Demo-Fibonacci-7")
                }   
            }   
        }
    }
}
question from:https://stackoverflow.com/questions/44003788/try-catch-block-in-jenkins-pipeline-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...