You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在@PicocliScript2注解的Groovy脚本中处理异常并返回退出码?

解决PicocliScript2脚本中异常处理与非零退出码问题

问题本质

@PicocliScript2 注解默认会捕获所有异常(包括参数解析错误),且默认返回0退出码——哪怕参数不完整,也只会输出提示信息而不抛出异常或返回非零码,导致Jenkins这类CI工具无法识别错误状态。

解决方案

以下两种纯脚本方式可实现异常处理并返回正确退出码:

方式1:自定义异常映射器

通过@PicocliScript2的exitCodeExceptionMapper属性指定自定义映射类,将不同类型的异常映射为对应非零退出码:

@PicocliScript2(
    exitCodeExceptionMapper = CustomExceptionMapper.class,
    mixinStandardHelpOptions = true
)
@Command(name = "greet", description = "Greets the user")
class GreetScript implements Runnable {
    @Option(names = ["-f", "--first-name"], required = true, description = "First name")
    String firstName

    @Option(names = ["-l", "--last-name"], required = true, description = "Last name")
    String lastName

    void run() {
        // 业务逻辑异常示例
        if (firstName.trim().isEmpty()) {
            throw new IllegalArgumentException("First name cannot be blank")
        }
        println "Hello, $firstName $lastName!"
    }
}

class CustomExceptionMapper implements ExitCodeExceptionMapper {
    int getExitCode(Exception ex) {
        if (ex instanceof ParameterException) { // 参数解析错误
            return 1
        } else if (ex instanceof IllegalArgumentException) { // 业务逻辑错误
            return 2
        }
        return 1 // 其他异常默认返回1
    }
}

方式2:手动控制CommandLine执行流程

放弃@PicocliScript2的自动执行逻辑,手动初始化CommandLine并处理执行结果,完全掌控异常与退出码:

@Command(name = "greet", description = "Greets the user", mixinStandardHelpOptions = true)
class GreetCommand implements Runnable {
    @Option(names = ["-f", "--first-name"], required = true, description = "First name")
    String firstName

    @Option(names = ["-l", "--last-name"], required = true, description = "Last name")
    String lastName

    void run() {
        if (firstName.trim().isEmpty()) {
            throw new IllegalArgumentException("First name cannot be blank")
        }
        println "Hello, $firstName $lastName!"
    }
}

// 手动处理命令执行流程
def cmd = new CommandLine(new GreetCommand())
try {
    int exitCode = cmd.execute(args)
    System.exit(exitCode)
} catch (Exception ex) {
    System.err.println("Error: ${ex.message}")
    System.exit(1)
}

效果验证

配置完成后,当参数不完整或触发业务异常时,脚本会返回对应非零退出码,Jenkins等CI工具会正确识别为任务失败,符合预期。

内容的提问来源于stack exchange,提问作者Asif Kamran Malick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 02:05:09