Dubl1n
Dubl1n

Reputation: 99

Jenkins error handling: using try/catch to post to log after build is complete and checked for errors

I have another question about Pipelines this time about error handling using try/catch. What I am doing is using the "try" outside the stage so I can easily tell which stages failed and which passed. And this has worked brilliantly.

I need to now worry about logging and success/failure for all our logs. So here is my dilemma: I want to it build (try) then error check (catch) then output SUCCESS if it has built and checked for errors. If the error check (catch) catches errors, then output to log FAILURE. I am sure the solution is staring at me in the face and I am missing it. This is what I have (simple version) that is not very elegant:

env.STAGE_STATUS = ""
try {
    stage ('Build Setup') {
        echo "Did this work?"
    }
} catch (errors) {
    echo "This did not work!"
    env.STAGE_STATUS = "FAIL"
}
if ("%STAGE_STATUS%" != "FAIL") {
    echo "This did work!"
}

As always thanks for any assistance.

Upvotes: 2

Views: 9323

Answers (1)

BigGinDaHouse
BigGinDaHouse

Reputation: 1356

Using try/catch/finally inside stage looks more elegant and at least more readable. Secondary if you want to fail build (which is basically same cause in your sample you are failing stage, which is also failing the job itself) use following var currentBuild.result, which is btw globally accessible. Saying so, I would go for this code:

stage('Build Setup') {
   try {
       echo 'Did this work?'
   } catch {
       echo 'This did not work!'
       currentBuild.result = 'FAILED'
   } finally {
       if (currentBuild.result != 'FAILED') {
           echo 'This did work!'
       }
   }
}

Upvotes: 1

Related Questions