如何在groovy中捕获异常?
在以下代码中:如何在groovy中捕获异常?,groovy,exception-handling,jenkins-groovy,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
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\u URL}”
在运行时插入
但是build()
方法中的catch
块未捕获第行抛出的异常(def data=newurl(${build\u 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)
如何处理异常?您的
executeBuildCommand
中至少有两个问题:
newurl(${BUILD\u URL})
表示您试图调用某个方法$
,该方法的唯一参数是闭包。您当然希望它看起来像newurl(${BUILD\u URL}”)
,以便插入BUILD\u URL
。或者为什么不直接使用新URL(BUILD\u URL)
$
,您会得到java.lang.NoSuchMethodError
。但是您试图捕获异常
,它不是NoSuchMethodError
的超类。后者将java.lang.Error
作为超类。如果您尝试捕获一个错误
,您就会看到您的消息为此错误引发异常是否有意义?为什么
executeBuildCommand()
中的catch()
没有捕获异常并传播到父方法build()
?不,它没有。你永远都不想捕捉错误
,除非你知道为什么要这样做。这些错误通常与我们编程的业务逻辑无关。它显示您的运行时出了问题。例如,NoSuchMethodError
(NSME)可能表明,由于某种原因,您希望存在的方法在运行时丢失。因此,您应该确保在下次运行代码时,该缺少的方法已就位NSME
会传播,但您的catch
两个块都无法捕捉Error
,因为它们被声明为捕捉Exception
,而它不是Error
的祖先。那么,捕捉每个错误的根类是什么呢?这是错误吗?因此,我将添加catch block,我的想法是使用try….catch在运行时捕获语法和运行时问题。其他功能问题,如连接超时或shell命令失败,则通过获取返回值来处理。那么,这是正确的方法吗?你的评论对我会有帮助的。