命令未找到

預設情況下,缺失的命令會透過 CommandNotFoundResultHandler 處理,並輸出一條簡單的訊息

shell:>missing
No command found for 'missing'

在內部,CommandNotFoundResultHandler 使用 CommandNotFoundMessageProvider,這是一個簡單的函式,接受一個 ProviderContext 並返回一個文字訊息。 下面是一個自定義訊息提供程式可能是什麼樣子的示例。

class CustomProvider implements CommandNotFoundMessageProvider {

	@Override
	public String apply(ProviderContext context) {
		// parsed commands without options
		List<String> commands = context.commands();
		// actual error, usually CommandNotFound exception
		Throwable error = context.error();
		// access to registrations at this time
		Map<String, CommandRegistration> registrations = context.registrations();
		// raw text input from a user
		String text = context.text();
		return "My custom message";
	}
}

可以透過將其定義為 bean 來更改此實現。

@Bean
CommandNotFoundMessageProvider provider1() {
	return new CustomProvider();
}

CommandNotFoundResultHandler 是一個函式式介面,因此可以編寫為 lambda。

@Bean
CommandNotFoundMessageProvider provider2() {
	return ctx -> "My custom message";
}