
[英]Is it possible to suppress the stack trace from a thrown Exception in groovy declarative pipelines?
[英]Groovy end exception different from exception thrown
在Groovy中,我遇到了一种极其奇怪的行为。 当我从脚本中的闭包引发异常时,所引发的最终异常有所不同。
以下是代码和详细信息:
public class TestDelegate {
def method(Closure closure) {
closure.setResolveStrategy(Closure.DELEGATE_FIRST);
closure.delegate = this;
closure.call();
}
public static void main(String[] args) {
// Make Script from File
File dslFile = new File("src/Script.dsl");
GroovyShell shell = new GroovyShell();
Script dslScript = shell.parse(dslFile);
TestDelegate myDelegate = new TestDelegate();
dslScript.metaClass.methodMissing = {
// will run method(closure)
String name, arguments ->
myDelegate.invokeMethod(name, arguments);
}
dslScript.metaClass.propertyMissing = {
String name ->
println "Will throw error now!"
throw new MyOwnException("errrrror");
}
dslScript.run();
}
}
class MyOwnException extends Exception {
public MyOwnException(String message) {
super(message);
}
}
Script.dsl:
method {
println a;
}
因此计划是,当我在TestDelegate
运行main()
方法时,它将运行DSL脚本,该脚本需要方法method()
。 在脚本中找不到它,它将调用methodMissing
,然后从myDelegate
调用method()
,后者又调用闭包,将委托设置为testDelegate
。 到现在为止还挺好。 然后,应该使用闭包尝试打印出未定义的“ a”,因此将引发propertyMissing
,这将引发MyOwnException
。
但是,当我运行代码时,将得到以下输出:
Will throw error now!
Exception in thread "main" groovy.lang.MissingPropertyException: No such property: a for class: TestDelegate
现在,它必须已经到达该catch块,因为它打印了“现在将抛出错误!”。 它一定也抛出了MyOwnException
! 但沿线某处, MyOwnException
转化为MissingPropertyException
,我不知道为什么。 有人有什么主意吗?
PS如果我从TestDelegate#method()
删除了closure.setResolveStrategy(Closure.DELEGATE_FIRST)
,则代码将按预期方式工作并抛出MyOwnException
。 但是我确实需要为我的DSL项目设置setResolveStrategy(Closure.DELEGATE_FIRST)
。 而且,我宁愿知道此问题的根本原因,而不是仅仅删除一两行,而在不了解原因的情况下看到它是否起作用。
我想这就是实际上发生的事情:使用委托,首先解决的策略,Groovy的运行时会首先尝试访问属性a
上myDelegate
,这会导致MissingPropertyException
,因为没有这样的属性存在。 然后,它尝试propertyMissing
,这将引发MyOwnException
。 最终,运行时放弃并抛出遇到的第一个异常(设计决策),恰好是MissingPropertyException
。
使用所有者优先解决策略,首先会查询propertyMissing
,因此最终会MyOwnException
。
查看下面的堆栈跟踪和源代码应提供更多证据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.