Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declarative vs Scripted Handling failures

I see on Declarative Pipeline that it's done via "post" section really easy with conditions like 'always', 'failure', ...:

https://jenkins.io/doc/book/pipeline/syntax/#post

But with Scripted Pipeline there are no examples on how it's done:

This link provides an example but only for "always" condition

https://jenkins.io/doc/book/pipeline/jenkinsfile/#handling-failures

I see this docs on how to set that result but I don't understand because with Declarative Pipeline you don't have to set it manually, plugins provided commands handle that for you.

https://support.cloudbees.com/hc/en-us/articles/218554077-How-to-set-current-build-result-in-Pipeline

Can anyone help me with this?

For example if I do this:

node { try { error 'Test error' } catch (ex) { echo 'Error handled' } }

It doesn't trigger the "FAILURE" build status automatically and I don't see the echo. Why?

like image 395
bdominguez Avatar asked Mar 17 '17 16:03

bdominguez


1 Answers

Your piece of code works as expected :

node { try { error 'Test error' } catch (ex) { echo 'Error handled' } }

gives :

[Pipeline] node
Running on maître in /var/lib/jenkins/workspace/test-pipeline2
[Pipeline] {
[Pipeline] error
[Pipeline] echo
Error handled
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

Explanations :

  1. error 'Test error' isn't supposed to log anything. It's equivalent to the Java throw new Exception("Test error"). See https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#code-error-code-error-signal
  2. the catch block catches this exception, and logs the message as expected. After this block, no error is thrown to the Jenkins runner, so the job ended as Successful.

If you want to mark your build as failed, you have to do this explicitly in the catch block. You can also use the catchError block to handle this for you. See : https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#code-catcherror-code-catch-error-and-set-build-result

like image 149
Mathieu L Avatar answered Oct 19 '22 10:10

Mathieu L