命令未找到

預設情況下,缺失的命令由 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";
}
© . This site is unofficial and not affiliated with VMware.