How to Use catchError in Jenkins Pipeline for Error Handling
In Jenkins Pipeline, use
catchError to catch errors in a block and control the build result without failing the entire pipeline. Wrap the code that might fail inside catchError to mark the build as unstable or continue running despite errors.Syntax
The catchError step wraps a block of code to catch any errors thrown inside it. You can specify options like buildResult to set the build status (e.g., 'UNSTABLE', 'FAILURE') and stageResult to set the stage status.
Basic syntax:
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
// code that might fail
}groovy
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') { // risky steps here }
Example
This example shows a Jenkins Declarative Pipeline where catchError is used to catch a failing shell command. Instead of failing the whole build, it marks the build as unstable and continues.
groovy
pipeline {
agent any
stages {
stage('Test catchError') {
steps {
catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
sh 'exit 1' // This command fails
}
echo 'This runs even if the above command fails.'
}
}
}
}Output
[Pipeline] {
[Pipeline] catchError
[Pipeline] {
[Pipeline] sh
+ exit 1
[Pipeline] }
[Pipeline] // catchError
[Pipeline] echo
This runs even if the above command fails.
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // pipeline
Finished: UNSTABLE
Common Pitfalls
- Not wrapping the exact failing step inside
catchErrorcauses the build to fail immediately. - Using
catchErrorwithout specifyingbuildResultdefaults to marking the build asFAILURE, which may not allow continuation. - Misunderstanding that
catchErroronly catches errors inside its block, so errors outside still fail the build.
groovy
/* Wrong usage: catchError outside the failing step */ catchError { echo 'This does not catch errors outside this block' } sh 'exit 1' // This will fail the build /* Correct usage: wrap the failing step */ catchError(buildResult: 'UNSTABLE') { sh 'exit 1' }
Quick Reference
catchError options:
buildResult: Sets the overall build status on error (e.g., 'UNSTABLE', 'FAILURE', 'SUCCESS').stageResult: Sets the stage status on error (e.g., 'FAILURE', 'UNSTABLE').message: Custom message to log on error.
Use catchError to handle errors gracefully and keep your pipeline running or mark it unstable instead of failing immediately.
Key Takeaways
Use catchError to catch errors inside a block and control build status without failing the pipeline.
Wrap only the steps that might fail inside catchError to handle errors precisely.
Specify buildResult and stageResult to set how Jenkins marks the build and stage on error.
Without catchError, any error will fail the entire pipeline immediately.
catchError helps keep pipelines running and provides better error handling and reporting.