Justin
Justin

Reputation: 507

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

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 or catchError block around the bat call, but then the step is marked as SUCCESS (green) even if the return code marks FAILURE (red).

Is there a way I can mark the stage as FAILURE on error and NOT stop the execution of the remaining demos? I don't want to break each demo run into different stages.

Upvotes: 1

Views: 1284

Answers (2)

Pexers
Pexers

Reputation: 1202

In declarative pipelines, you can achieve this using the catchError block, 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 FAILURE in case of exception, but the remaining demos and following stage will execute regardless.

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

See also:

Upvotes: 2

ycr
ycr

Reputation: 14604

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")
        }
    }
}

Upvotes: 1

Related Questions