Home > Enterprise >  How can I mark a stage as FAILED but continue its execution in Jenkins?
How can I mark a stage as FAILED but continue its execution in Jenkins?

Time:01-11

Here's my code, it uses jenkins-plugin

pipeline
{
    agent any
    stages
    {
        stage ('Run Demos')
        {
            def demoPath = '"'   env.WORKSPACE   'MyDemo.exe"'
            def demoNames = ["demo1", "demo2"]
            for (demoName in demoNames)
            {
                bat('start /b /wait "" '   demoPath   ' '   demoName)
            }
        }
    }
}

When bat('start /b /wait "" ' demoPath ' ' demoName) fails inside the loop, the whole stage is stopped. I can workaround this by adding a try/catch block or catch error around the bat call, but then the step is marked as green even if the return code marks failure.

Is there a way I can still mark the stage as red on error, but NOT stop the execution of that stage? I don't want to break each demo run into different stages.

CodePudding user response:

In declarative pipelines you can achieve this using catchError, like so:

stage ('Run Demos')
{
    steps 
    {
        def demoPath = '"'   env.WORKSPACE   'MyDemo.exe"'
        def demoNames = ["demo1", "demo2"]
        for (demoName in demoNames)
        {
            catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') 
            {
                bat('start /b /wait "" '   demoPath   ' '   demoName)
            }
        }
    }
}

The overall build as well as the stage will be marked as FAILED in case of exception, but the rest of the stages will execute regardless.

Use SUCCESS or null to keep the buildResult from being set when an error is caught.

See also:

CodePudding user response:

Another option is to use currentBuild.result to set the status in the catch block.

script {
    for (demoName in demoNames) {
        try {
            bat('start /b /wait "" '   demoPath   ' '   demoName)
        } catch (e) {
            currentBuild.result = 'FAILURE'
            unstable("One of the demos failed")
        }
    }
}
  • Related