Skip to main content

Implementing Pipeline Error Handling

1. Using Try-Catch Blocks

Block Description Usage
try Defines a block of code to be executed
try {
  // Code that might throw an exception
}
catch Defines a block of code to handle errors
catch (Exception e) {
  // Handle the exception
}
finally Defines a block of code to run regardless of whether an error occurred
finally {
  // Cleanup code
}

Example: Basic Try-Catch in Jenkins Pipeline

pipeline {
  agent any
  stages {
    stage('Example') {
      steps {
        script {
          try {
            sh 'echo "Running command..."'
            sh 'exit 1' // Simulate failure
          } catch (e) {
            echo "Caught an exception: ${e}"
            currentBuild.result = 'FAILURE'
          } finally {
            echo "Cleanup actions here"
          }
        }
      }
    }
  }
}
Note: The catch block will only execute if an exception is thrown within the try block. The finally block always executes, regardless of whether an exception was thrown or not.

2. Implementing Error Recovery Strategies

Strategy Description Usage
retry Retries a step up to a specified number of times on failure
retry(times: 3) {
    sh 'some-command-that-might-fail'
}
catchError Captures errors and allows custom handling or logging
catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
    sh 'some-failing-command'
}
post Executes actions after pipeline completion, including on failure
post {
    failure {
        echo 'Pipeline failed'
    }
}

Example: Using retry with catchError

pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                    retry(times: 2) {
                        sh 'deploy-to-staging.sh'
                    }
                }
            }
        }
    }
}
Note: retry is useful for transient failures like network issues. catchError allows more granular control over error handling and can prevent pipeline termination.
Warning: Be cautious with retry in production environments as it can lead to resource exhaustion if not bounded properly.

3. Using catchError Step

Parameter Description Values
catchError Step to handle errors in a pipeline catchError

Example: Basic catchError usage

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                catchError(buildResult: 'FAILURE', errorCode: 'ERROR123') {
                    sh 'exit 1'
                }
            }
        }
    }
}

Example: catchError with fallback stage

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh 'echo "Building..."'
            }
        }
        stage('Test') {
            steps {
                catchError(stageName: 'Test', buildResult: 'FAILURE') {
                    sh 'echo "Running tests..."'
                    sh 'exit 1'
                }
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying...'
            }
        }
    }
}
Note: The catchError step allows you to define a fallback behavior when a stage fails. It can capture the failure and continue execution or mark the build as unstable.
Warning: Using catchError does not prevent the overall pipeline from failing if the build result is set to FAILURE. It only allows for handling of the error within the scope of the step.

4. Handling Stage Failures

Property Description Values
stage.name Name of the stage build, test, deploy
stage.status Current status of the stage success, failure, unstable
stage.result Result of the stage execution success, failure, aborted

Example: Stage Failure Handling

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh 'echo "Building..."'
            }
            post {
                failure {
                    echo 'Build failed!'
                }
            }
        }
    }
}
Note: The post block allows defining actions that run after a stage completes, regardless of its outcome.

Common Post Actions for Stage Failures

  • failure: Executes if the stage fails.
  • success: Executes if the stage succeeds.
  • always: Executes regardless of stage outcome.

5. Using warnError for Non-Blocking Errors

The warnError directive in Jenkins Pipeline allows you to handle errors without stopping the pipeline execution. It's particularly useful for scenarios where a failure in one step shouldn't halt the entire build process.

Directive Description Usage
warnError Continues pipeline execution even if a step fails warnError 'Build failed' { sh 'exit 1' }

Example: warnError in Action

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                script {
                    warnError 'Build failed, but continuing' {
                        sh 'echo "Starting build..."'
                        sh 'exit 1'
                    }
                    echo 'Continuing with next stage...'
                }
            }
        }
    }
}
Note: warnError does not stop the pipeline but logs the error and continues execution. It's ideal for optional or non-critical steps.

6. Implementing Retry Logic

Property Values Description
retryCount 3 Number of times to retry a failed step
retryDelay 10 Delay in seconds between retries

Example: Retry Logic in Jenkins Pipeline

pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                retry(count: 3, delay: 10) {
                    sh 'kubectl apply -f deployment.yaml'
                }
            }
        }
    }
}
Note: The retry block will attempt to execute the enclosed steps up to the specified number of times with a delay between each attempt.

7. Setting Timeout Handling

Property Values Description
timeout timeUnit Defines the maximum time a stage can run before it is terminated. Supported units: seconds, minutes, hours.
timeUnit seconds, minutes, hours Unit of time for the timeout value. Default is minutes.

Example: Timeout in a Pipeline Stage

pipeline {
    agent any
    stages {
        stage('Build') {
            timeout(time: 5, unit: 'MINUTES') {
                steps {
                    sh 'echo "Building project..."'
                }
            }
        }
    }
}
Note: If a stage exceeds the specified timeout, Jenkins will terminate it and mark the build as failed.

8. Using unstable Result Status

Result Status Description Usage
SUCCESS Build completed successfully with no failures. Default status when all stages pass.
UNSTABLE Build completed with warnings or non-fatal failures. Used when tests fail but build is still considered acceptable.
FAILURE Build failed due to test failures or build errors. Build is marked as broken; requires attention.
ABORTED Build was manually stopped or interrupted. Used when a user cancels the build process.

Example: Setting Unstable Status in Pipeline

pipeline {
    agent any
    stages {
        stage('Test') {
            steps {
                script {
                    try {
                        sh 'npm test'
                    } catch (e) {
                        currentBuild.result = 'UNSTABLE'
                        echo "Tests failed but build is stable"
                    }
                }
            }
        }
    }
}
Note: Setting currentBuild.result = 'UNSTABLE' does not stop the pipeline execution, but marks it as unstable for reporting and notifications.

9. Propagating Errors Across Stages

Property Description Default Value Notes
error Represents an error that occurred in a stage or step. null Used to capture and propagate errors in pipelines.
currentBuild.result Current result of the build (e.g., SUCCESS, FAILURE). UNSTABLE Can be set to FAILURE or ABORTED to propagate errors.

Example: Setting Build Result to Fail

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh 'echo "Building..."'
            }
        }
        stage('Test') {
            steps {
                sh 'echo "Testing..."'
                script {
                    try {
                        sh 'exit 1'
                    } catch (e) {
                        currentBuild.result = 'FAILURE'
                        throw e
                    }
                }
            }
        }
    }
}
Note: Setting currentBuild.result to FAILURE ensures that the pipeline stops and marks the build as failed.
Warning: If errors are not explicitly handled or propagated, they may be silently ignored in downstream stages.

10. Using Error Notification Strategies

Strategy Description Configuration Notes
Email Notifications Sends email alerts on pipeline failures emailext plugin configuration Requires SMTP server setup
Slack Integration Posts error messages to Slack channels slack plugin settings Supports webhook and bot integration
Webhook Alerts Triggers external HTTP endpoints on failure post block with httpRequest Can send to any REST API or service
Jira Integration Creates or updates Jira issues for build failures jira plugin configuration Requires Jira server or cloud access

Example: Slack Notification on Failure

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh 'echo "Building..."'
            }
        }
    }
    post {
        failure {
            slackSend channel: '#build-notifications', message: "Build failed: ${env.BUILD_URL}"
        }
    }
}
Note: Error notification strategies should be configured with appropriate permissions and security measures to prevent abuse or unauthorized access.

Was this article helpful?