Groovy脚本使用assert抛出异常后无限挂起的原因及解决方法
Groovy脚本执行assert异常后无限挂起的原因与修复
问题原因
Groovy默认的断言(assert)机制在抛出AssertionError时,会触发交互式异常处理流程——特别是在控制台运行脚本时,Groovy会尝试等待用户输入(比如询问是否进入调试模式),这就导致脚本卡在异常输出后的交互环节,无法自动终止,必须手动中断。
修复方案
有三种可行的解决方式,按需选择:
1. 通过启动参数禁用交互式断言
运行脚本时添加JVM参数-Dgroovy.assert.failfast=true,让assert失败后直接终止进程,跳过交互环节:
groovy -Dgroovy.assert.failfast=true verify.groovy
2. 在脚本内捕获异常并主动退出
修改verify.groovy,用try-catch包裹evaluate调用,捕获AssertionError后打印错误信息并主动结束进程:
[ 'first-check.groovy', 'second-check.groovy' ].each { try { evaluate(basedir.toPath().resolve(it).toFile()) println String.format('Verified with %s - OK', it) } catch (AssertionError e) { println String.format('Verification failed with %s: %s', it, e.message) System.exit(1) // 立即终止脚本进程 } }
3. 使用GroovyShell替代evaluate执行脚本
GroovyShell提供了更可控的脚本执行环境,默认不会触发交互式断言处理,结合异常捕获可以避免挂起:
import groovy.lang.GroovyShell def shell = new GroovyShell() [ 'first-check.groovy', 'second-check.groovy' ].each { try { shell.evaluate(basedir.toPath().resolve(it).toFile()) println String.format('Verified with %s - OK', it) } catch (AssertionError e) { println String.format('Verification failed with %s: %s', it, e.message) System.exit(1) } }
内容的提问来源于stack exchange,提问作者Volodya Lombrozo
相关产品推荐
相关产品推荐

