I found SO question Determine Failed Stage in Jenkins Declarative Pipeline with answers suggesting to use PipelineNodeGraphVisitor or FlowGraphTable to access the failed stages/steps. But I think those would only yield the error messages maybe, and not the escaped exception with whatever metadata it could carry?..
You might have noticed that handling exceptions in Declarative Pipeline is a bit more limited compared to Scripted Pipeline. As far as I know, in Declarative syntax, there isn’t a straightforward way to catch exceptions directly, especially if you want to inspect what went wrong (like checking for a timeout versus another kind of failure).
That being said, I think there are a few approaches that could help, depending on how much flexibility you need.
What You Can Do in Declarative
You can use the post block to respond to general outcomes like failure, aborted, or unstable. This is useful for cleanup or notifications, for example. However, it’s worth noting that you don’t get access to the actual exception or its details within that block, just the final build status.
If You Need to Look at the Exception
If you’re trying to distinguish between different types of failures (like a timeout versus an external interruption), you’ll probably need to use a script block. Inside that, you can use try/catch to handle things in a more fine-grained way, similar to Scripted Pipeline.
Here’s an (untested) example that shows one way this could work:
pipeline {
agent any
stages {
stage('Timeout Example') {
steps {
script {
try {
timeout(time: 1, unit: 'SECONDS') {
sleep(60)
}
} catch(org.jenkinsci.plugins.workflow.steps.FlowInterruptedException e) {
echo "${e.causes}"
if (e.causes.find { it instanceof org.jenkinsci.plugins.workflow.steps.TimeoutStepExecution$ExceededTimeout }) {
echo "Looks like we hit a timeout."
} else {
echo "Interrupted for a different reason."
}
} catch(e) {
echo "Something else might have gone wrong."
}
}
}
}
}
}
This pattern could be useful if your pipeline logic depends on why something failed, not just that it failed.
To Summarize
Pure Declarative pipelines don’t give you access to the exception object, only the build status via post blocks.
If you need to catch and inspect exceptions, dropping into a script block is likely the best option.
The workaround above might be worth trying if you’re dealing with timeouts or similar cases.
Welp, that was the main confirmation that I wanted to hear.
The original question came from a discussion with other folks where they already had a complex declarative pipeline with many stages, and were looking to enrich their post{} block with some switch(error_type) without the need to wrap every single stage in try-catch.
One more reason for me to strengthen my beliefs in the scripted pipeline superiority, I guess