catchError
step.
The behavior of the step when an exception is thrown can be configured to print
a message, set a build result other than failure, change the stage result,
or ignore certain kinds of exceptions that are used to interrupt the build.
This step is most useful when used in Declarative Pipeline or with the
options to set the stage result or ignore build interruptions. Otherwise,
consider using plain try
-catch
(-finally
) blocks.
It is also useful when using certain post-build actions (notifiers)
originally defined for freestyle projects which pay attention to the result of the ongoing build.
node { catchError { sh 'might fail' } step([$class: 'Mailer', recipients: 'admin@somewhere']) }
If the shell step fails, the Pipeline build’s status will be set to failed, so that the subsequent mail step will see that this build is failed. In the case of the mail sender, this means that it will send mail. (It may also send mail if this build succeeded but previous ones failed, and so on.) Even in that case, this step can be replaced by the following idiom:
node { try { sh 'might fail' } catch (err) { echo "Caught: ${err}" currentBuild.result = 'FAILURE' } step([$class: 'Mailer', recipients: 'admin@somewhere']) }
For other cases, plain try
-catch
(-finally
) blocks may be used:
node { sh './set-up.sh' try { sh 'might fail' echo 'Succeeded!' } catch (err) { echo "Failed: ${err}" } finally { sh './tear-down.sh' } echo 'Printed whether above succeeded or failed.' } // …and the pipeline as a whole succeeds
See this document for background.