How to throw exception in jenkins pipeline?
This is how I do it in Jenkins 2.x.
Notes: Do not use the error signal, it will skip any post steps.
stage('stage name') {
steps {
script {
def status = someFunc()
if (status != 0) {
// Use SUCCESS FAILURE or ABORTED
currentBuild.result = "FAILURE"
throw new Exception("Throw to stop pipeline")
// do not use the following, as it does not trigger post steps (i.e. the failure step)
// error "your reason here"
}
}
}
post {
success {
script {
echo "success"
}
}
failure {
script {
echo "failure"
}
}
}
}
It seems no other type of exception than Exception
can be thrown. No IOException
, no RuntimeException
, etc.
This will work:
throw new Exception("Something went wrong!")
But these won't:
throw new IOException("Something went wrong!")
throw new RuntimeException("Something went wrong!")
If you want to abort your program on exception, you can use pipeline step error
to stop the pipeline execution with an error. Example :
try {
// Some pipeline code
} catch(Exception e) {
// Do something with the exception
error "Program failed, please read logs..."
}
If you want to stop your pipeline with a success status, you probably want to have some kind of boolean indicating that your pipeline has to be stopped, e.g:
boolean continuePipeline = true
try {
// Some pipeline code
} catch(Exception e) {
// Do something with the exception
continuePipeline = false
currentBuild.result = 'SUCCESS'
}
if(continuePipeline) {
// The normal end of your pipeline if exception is not caught.
}