Luckily, there is a better solution. We can combine both catchError with the try-catch . Let’s take a look at the final example.

Listing 4. Jenkinsfile pipeline { agent any stages { stage("A") { options { timeout(time: 3, unit: "SECONDS") } steps { script { Exception caughtException = null catchError(buildResult: 'SUCCESS', stageResult: 'ABORTED') { (1) try { (2) echo "Started stage A" sleep(time: 5, unit: "SECONDS") } catch (org.jenkinsci.plugins.workflow.steps.FlowInterruptedException e) { error "Caught ${e.toString()}" (3) } catch (Throwable e) { caughtException = e } } if (caughtException) { error caughtException.message } } } } stage("B") { steps { echo "Started stage B" } } } }

In this example, we use catchError to control the stage result in case of an error . The code that may potentially timeout is wrapped with the try-catch so we can control the exception. We can be very specific - in this case we catch the FlowInterruptedException to mark the current stage as ABORTED , but we also store any other exception as caughtException . If any exception other than FlowInterruptedException occurs, we execute error step with an exception message to fail the A stage. Let’s run and see the final result.

And here is what happens if the code that may timeout throws a different error (for instance, some shell command may return exit code 1.)

Voilà! Now it works just as we expect. The A stage gets executed, and it is acceptable to timeout. The pipeline continues in such a case, and its final result depends on the remaining stages.

Thank you!

Thank you so much for reading up to this point! I hope this article met your expectations, and you have learned something valuable from it. If you have one more minute, leave me a comment below, please. This way, I can thank you for your time more in person.

And last but not least. If you find this blog post valuable, help me spread the word, please. You can share it on Twitter, LinkedIn, or anywhere else you can think of. This single tweet or post on social media helps a lot. One more time - thank you so much! You’re awesome!