退出程式碼對映

退出程式碼的預設行為如下

  • 命令選項解析中的錯誤將導致程式碼 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();
無法使用基於註解的配置自定義退出程式碼