【发布时间】:2020-09-18 00:31:09
【问题描述】:
当 groovy 代码调用一个不存在的方法时,有没有办法捕获 NoSuchMethodError 错误?
以下代码会导致 NoSuchMethodError 错误,该错误未被捕获,但 finally 块确实执行。这会导致我的一些错误处理和报告出现问题。
使用伪造 dsl 的代码
try {
println "in try"
dslDoesNotExist()
} catch (Exception ex) {
println "Caught error ${ex}"
throw ex
} finally {
println "finally block"
}
结果
in try
[Pipeline] echo
finally block // see the finally but not the catch
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.lang.NoSuchMethodError: No such DSL method 'dslDoesNotExist'
如果我修改代码以引用不存在的属性/变量,则处理 catch 块
缺少属性的代码
try {
println "in try"
propertyOrVariableDoesNotExist
} catch (Exception ex) {
println "Caught error ${ex}"
throw ex
} finally {
println "finally block"
}
结果
in try
[Pipeline] echo
Caught error groovy.lang.MissingPropertyException: No such property: propertyOrVariableDoesNotExist for class: WorkflowScript
[Pipeline] echo
finally block
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
hudson.remoting.ProxyException: groovy.lang.MissingPropertyException: No such property: propertyOrVariableDoesNotExist for class:
这里发生了什么
Java 与 Groovy 异常?
CPS groovy catch(Exception ex) 能否捕获 java.lang。例外?没有
代码
try {
throw new java.lang.NoSuchMethodError("dsl problem")
} catch (Exception ex) {
println "Caught"
}
结果
// No evidence of the catch
[Pipeline] { (hide)
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
java.lang.NoSuchMethodError: dsl problem
【问题讨论】:
-
这段代码的上下文是什么?它是库、全局变量、脚本块还是原生脚本 DSL?您希望该方法在哪里正常定义?另请注意,您试图在第一个不成功示例中捕获 Groovy 中的 Java 异常,并在第二个成功示例中捕获 Groovy 中的 Groovy 异常。
-
上下文是代码从另一个 repo 加载 groovy 代码。如果选择的 repo 分支缺少该方法,那么我们就会遇到这个问题。我以为 catch 会抓住一切,但事实并非如此
-
我也试过 catch(java.lang.NoSuchMethodError){...} 也没有用。
标签: groovy jenkins-pipeline jenkins-groovy