将 Java 异常传递给 JenkinsFile

Passing Java exception to JenkinsFile

我正在调用 Java class 作为我的 Jenkins pipleine 的一部分。我想根据从主 class 返回的异常通过或失败管道。我正在尝试这样的事情。

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    
    }
  }
} 

但是从 Jenkins 日志中,我看到原始异常没有被传递。

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

是否可以在 Jenkins 文件中获取实际消息? 注意:getStackTrace 不允许用于我们的管道。

你捕获的异常(InvocationTargetException)不是java class(com..test.Deployer)抛出的,而是sh步骤抛出的,所以有没有关于您的 class com..test.Deployer.

的消息或 stackTrace

同时,sh step 没有提供捕获 stderr 的好方法,并且 shreturnStdout 参数在脚本错误退出时不起作用。

有一个工作台可以获取 mvn 输出,方法是使用 -DoutputFile

将 mvn 输出写入临时文件
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    
        }
    }
}

错误消息将在 errmsg = readFile(stderrfile).