退出代码映射
退出代码的默认行为如下:
-
命令选项解析错误将导致代码为
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();
基于注解的配置无法自定义退出代码。 |