How do you handle errors in scripted pipeline correctly?
IntermediateConceptScripted pipeline, Groovy & CPS
Answer
Use try/catch/finally, rethrow after handling, and never swallow FlowInterruptedException (user abort or timeout), or the build will keep running after someone clicked Abort.
try {
sh './deploy.sh'
} catch (org.jenkinsci.plugins.workflow.steps.FlowInterruptedException e) {
throw e
} catch (err) {
currentBuild.result = 'FAILURE'
slackSend channel: '#deploys', message: "Deploy failed: ${err}"
throw err
} finally {
sh 'rm -f kubeconfig'
}
More on Scripted pipeline, Groovy & CPS
What does a scripted pipeline look like and when would you still write one?IntermediateWhat is CPS and why does Jenkins transform pipeline Groovy?AdvancedWhy does `java.io.NotSerializableException` happen in pipelines?AdvancedWhat does `@NonCPS` do and what are its rules?AdvancedWhy do some Groovy closures behave unexpectedly in pipelines, for example `list.each { }` or `sort`?AdvancedWhat is the `script` block in declarative, and what are its limits?Beginner