Search code examples
jenkinsgroovyjenkins-pipelinejenkins-groovy

Jenkinsfile - stop pipeline when catch error


I am having a problem with my pipeline in Jenkins.

I perform a path search for files with the specified extension. I then execute php -l with the previously found files. Everything works okay but I would like if php -l finds an error then the build and step go to UNSTABLE state and further execution of the pipeline is stopped. I managed to do it this way but then build and step are in a FAILED state

} catch (Exception e) {
            error("${e}")

Part of code my pipeline.

def check(){
    stage('Validate files') {
        try {
            sh "find . -type f -iregex '.*\\.\\(php\\)' | xargs -I % sh -c 'php -l \'%\''" 
        } catch (Exception e) {
            error("${e}")
        }
    }
}

I hope someone smarter can direct me to a solution :)


Solution

  • Got an example to work but maybe not exactly what you wanted. I used unstable() to mark the stage / build and then checked for the exit code of the sh step to return or continue the pipeline.

    There are 2 if's as you need to return outside of a stage to not just return from the stage.

    #!/usr/bin/env groovy
    
    try {
        node {
            def exitCode = 0
            exitCode = check()
            if (exitCode != 0){
                return
            }
            somethingelse()
        }
    } catch (Throwable err) { // catch all exceptions
            throw err
    } finally {}
    
    def check(){
        stage('Validate files') {
                exitCode = sh script:"exit 1", returnStatus:true
                if (exitCode !=0){
                    unstable('message')
                }
            }
        return exitCode
    }
    
    def somethingelse(){
        stage('Something'){
                echo "somethingelse"
        }
    }