0
0
JenkinsDebug / FixBeginner · 4 min read

How to Handle Errors in Jenkins Pipeline: Simple Fixes

In Jenkins pipelines, handle errors by wrapping risky steps in try-catch blocks or using post sections to catch failures. This lets you control what happens on errors, like sending notifications or cleaning up resources.
🔍

Why This Happens

Errors in Jenkins pipelines happen when a step fails, like a build or test command returning a non-zero exit code. Without error handling, the pipeline stops immediately and may not run cleanup or notification steps.

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                sh 'exit 1' // This command fails
            }
        }
    }
}
Output
[Pipeline] sh + exit 1 [Pipeline] // sh [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // pipeline ERROR: script returned exit code 1 Finished: FAILURE
🔧

The Fix

Wrap the risky step in a try-catch block to catch errors and handle them gracefully. You can also use the post section to run actions after success or failure.

groovy
pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                script {
                    try {
                        sh 'exit 1' // This command fails
                    } catch (err) {
                        echo "Caught error: ${err}"
                        // Handle error, e.g., notify or mark unstable
                    }
                }
            }
        }
    }
    post {
        failure {
            echo 'Build failed, sending notification.'
        }
    }
}
Output
[Pipeline] script [Pipeline] { [Pipeline] sh + exit 1 [Pipeline] // sh [Pipeline] catchError Caught error: script returned exit code 1 [Pipeline] } [Pipeline] // script [Pipeline] } [Pipeline] // stage [Pipeline] post [Pipeline] { [Pipeline] echo Build failed, sending notification. [Pipeline] } [Pipeline] // post [Pipeline] } [Pipeline] // pipeline Finished: SUCCESS
🛡️

Prevention

To avoid pipeline errors stopping your entire process unexpectedly, always use try-catch blocks around commands that might fail. Use post sections to clean up or notify on failure. Also, test your pipeline scripts in a safe environment before running in production.

⚠️

Related Errors

  • Timeout errors: Use timeout blocks to handle long-running steps.
  • Missing credentials: Ensure credentials are properly configured and accessed with withCredentials.
  • Syntax errors: Validate pipeline syntax with the Pipeline Syntax tool in Jenkins.

Key Takeaways

Use try-catch blocks in Jenkins pipelines to catch and handle errors gracefully.
Leverage post sections to run cleanup or notifications after failures.
Always test pipeline scripts in a safe environment before production.
Handle common related errors like timeouts and credential issues proactively.