Issue
I am invoking a Java class as part of my Jenkins pipleine. I want to pass or fail the pipeline based on the exception retureeened from the main class. I am trying something like this.
script{
try{
sh ' mvn exec:java -Dexec.mainClass="com..test.Deployer" -Dexec.args="qal"'
}catch (Exception e) {
echo 'exception::' + e.toString()
echo 'message::' + e.getMessage()
echo 'cause::' + e.getCause()
if (e.toString().contains("NoChangeDetectedException")) {
currentBuild.result = 'SUCCESS'
return
}
}
}
But from the Jenkins log, I see the original exception is not getting passed.
An exception occured while executing the Java class. null: InvocationTargetException:
exception:: hudson.AbortException: script returned exit code 1
message:: script returned exit code 1
cause:: null
Is it possible to get the actual message in the Jenkins file?
Note: getStackTrace
is not permitted for our pipeline.
Solution
The exception(InvocationTargetException) you caught is not threw by java class(com..test.Deployer), it is threw by sh
step, so there is no message or stackTrace about your class com..test.Deployer
.
Meanwhile, sh
step doesn't provide a good way to capture stderr, and the returnStdout
parameter of sh
doesn't work when script exit with error.
There is a workground to get the mvn output, by write mvn output to a temp file, using -DoutputFile
script {
stderrfile = 'stderr.out' //temp file
shout = '' //doesn't work for this question
try{
shout = sh(returnStdout: true, script: "mvn exec:java -Dexec.mainClass='com..test.Deployer' -Dexec.args='qal' -DoutputFile=${stderrfile}")
echo 'shout::' + shout
}catch (Exception e) {
errmsg = readFile(stderrfile)
echo 'errmsg::' + errmsg
echo 'shout::' + shout
echo 'exception::' + e.toString()
echo 'message::' + e.getMessage()
echo 'cause::' + e.getCause()
if (e.toString().contains("NoChangeDetectedException")) {
currentBuild.result = 'SUCCESS'
return
}
}
}
The error message will be in the errmsg = readFile(stderrfile)
.
Answered By - tianzhipeng