如何在Groovy中捕获异常?

时间:2019-02-22 15:54:02

标签: groovy exception-handling jenkins-groovy

在下面的代码中:

def build(arg1, arg2, arg3, arg4, arg5){

    try{

        executeBuildCommand(commandString, component)
    }
    }catch(Exception e){

        print ' build() method raised exception'
        print "Error cause: ${e}"
        error('Build stage - failed')
    }
}


def executeBuildCommand(arg1, arg2){

    try{
        // BUILD_FULL = sh('build the code')

        if(BUILD_FULL == true){
            def data = new URL(${BUILD_URL}).getText()
        }        
    }catch(Exception e){
        throw e
    }   
}

我了解到"${BUILD_URL}"在运行时进行插值

但是catch方法中的build()块不能捕获在行(def data = new URL(${BUILD_URL}).getText())上抛出的异常

相反,我收到异常堆栈

java.lang.NoSuchMethodError: No such DSL method '$' found among steps [ArtifactoryGradleBuild, MavenDescriptorStep, acceptGitLabMR, 
addGitLabMRComment, addInteractivePromotion, ansiColor, archive, artifactoryDistributeBuild,... ]  or 
globals [Artifactory, LastChanges, currentBuild, docker, env, params, pipeline, scm]
    at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:201)
    at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:122)

如何处理异常?

1 个答案:

答案 0 :(得分:2)

您的executeBuildCommand中至少有两个问题:

  1. new URL(${BUILD_URL})意味着您正在尝试调用某个方法$,该方法将闭包作为唯一参数。为了插入new URL("${BUILD_URL}"),您当然希望它看起来像BUILD_URL。还是为什么不只使用new URL(BUILD_URL)
  2. 作为第1点的结果,您得到java.lang.NoSuchMethodError的{​​{1}}。但是,您尝试捕获不是$的超类的Exception。后者具有NoSuchMethodError作为超类。如果您尝试捕获java.lang.Error,则会看到您的邮件