How to fail a single stage through plugin?

Currently we are developing a Jenkins plugin as a Step. Now in case of errors we want to fail the single stage from where our step is called in Jenkinsfile. We’ve got a way to mark the whole build as failed but we want the next stages should execute but our stage should be failed in case of error. How can we achieve that through our plugin?

Note- We are using Jenkins version 2.401.3

In Jenkins, if a stage fails, the default behavior is to stop the entire pipeline. However, I think you could change this behavior by using the catchError or catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') step in your Jenkinsfile.
This should allow the pipeline to continue even if a stage fails.

Here is an untested example of how you could maybe use catchError in your Jenkinsfile:

pipeline {
    agent any
    stages {
        stage('Stage 1') {
            steps {
                // Your steps here
            }
        }
        stage('Stage 2') {
            steps {
                script {
                    catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
                        // Call your plugin here
                    }
                }
            }
        }
        stage('Stage 3') {
            steps {
                // Your steps here
            }
        }
    }
}

In this example, if your plugin (called in Stage 2) fails, the stage will be marked as failed but the pipeline will continue to Stage 3.
Please note that the catchError step is part of the Pipeline Basic Steps plugin, which should be installed and available in most Jenkins environments (93% at the time of writing).
As for marking the stage as failed from within your plugin, you would need to throw an exception when an error occurs in your plugin. This will cause the catchError step to mark the stage as failed.

Here’s a simple example in Java:

public class YourPluginStep extends Step {
    @Override
    public StepExecution start(StepContext context) throws Exception {
        // Your plugin code here

        if (/* error condition */) {
            throw new AbortException("Error message");
        }

        return new YourPluginStepExecution(context);
    }
}

In this example, if the error condition is met, an AbortException is thrown, which will cause the catchError step to mark the stage as failed.

Hope this helps. :person_shrugging:

1 Like

Thanks @poddingue. Appreciate it.

1 Like