退出代码映射

退出代码的默认行为如下

  • 命令选项解析中的错误将导致代码 2

  • 任何一般性错误都将导致代码 1

  • 显然,在任何其他情况下,结果代码都是 0

每个 CommandRegistration 都可以定义其自身 Exception 和*退出代码* 之间的映射。 本质上,我们受限于 Spring Boot 中关于*退出代码* 的功能,并且只是集成到其中。

假设存在以下异常,该异常将从命令中抛出

static class MyException extends RuntimeException {

	private final int code;

	MyException(String msg, int code) {
		super(msg);
		this.code = code;
	}

	public int getCode() {
		return code;
	}
}

可以定义 Throwable 和退出代码之间的映射函数。您也可以只配置一个 退出代码,这只是配置中的一个语法糖。

CommandRegistration.builder()
	.withExitCode()
		.map(MyException.class, 3)
		.map(t -> {
			if (t instanceof MyException) {
				return ((MyException) t).getCode();
			}
			return 0;
		})
		.and()
	.build();
无法使用基于注解的配置自定义退出代码