此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Shell 3.3.3spring-doc.cadn.net.cn

@ExceptionResolver

@ShellComponent类可以具有@ExceptionResolver处理 Component 异常的方法 方法。这些用于带 Comments 的方法。spring-doc.cadn.net.cn

该异常可能与正在传播的顶级异常匹配(例如,直接的 IOException 被抛出)或针对包装器异常中的嵌套原因(例如,包装的 IOException 在 IllegalStateException 中)。这可以在任意原因级别匹配。spring-doc.cadn.net.cn

对于匹配的异常类型,最好将目标异常声明为方法参数,如 前面的示例显示了。当多个异常方法匹配时,根异常匹配为 通常优先于 Cause 异常匹配。更具体地说,ExceptionDepthComparator 用于根据异常从引发的异常类型中对异常的深度对异常进行排序。spring-doc.cadn.net.cn

或者,注解声明可以缩小要匹配的异常类型,因为 以下示例显示:spring-doc.cadn.net.cn

@ExceptionResolver({ RuntimeException.class })
CommandHandlingResult errorHandler(Exception e) {
	// Exception would be type of RuntimeException,
	// optionally do something with it
	return CommandHandlingResult.of("Hi, handled exception\n", 42);
}
@ExceptionResolver
CommandHandlingResult errorHandler(RuntimeException e) {
	return CommandHandlingResult.of("Hi, handled custom exception\n", 42);
}

@ExceptionResolver也可以返回String用作 console 的输出。您可以 用@ExitCode注解来定义返回代码。spring-doc.cadn.net.cn

@ExceptionResolver
@ExitCode(code = 5)
String errorHandler(Exception e) {
	return "Hi, handled exception";
}

@ExceptionResolvervoidreturn 类型会自动作为 Handled Exception 处理。 然后,您还可以定义@ExitCode并使用Terminal如果你需要写点什么 进入控制台。spring-doc.cadn.net.cn

@ExceptionResolver
@ExitCode(code = 5)
void errorHandler(Exception e, Terminal terminal) {
	PrintWriter writer = terminal.writer();
	String msg =  "Hi, handled exception " + e.toString();
	writer.println(msg);
	writer.flush();
}

方法参数

@ExceptionResolver方法支持以下参数:spring-doc.cadn.net.cn

Method 参数 描述

异常类型spring-doc.cadn.net.cn

用于访问引发的异常。这是任何类型的ExceptionThrowable.spring-doc.cadn.net.cn

终端spring-doc.cadn.net.cn

对于底层JLineterminal 更改为 即 get its terminal writer。spring-doc.cadn.net.cn

返回值

@ExceptionResolver方法支持以下返回值:spring-doc.cadn.net.cn

返回值 描述

字符串spring-doc.cadn.net.cn

用于返回到 shell 的纯文本。在本例中,使用退出代码 1。spring-doc.cadn.net.cn

CommandHandlingResultspring-doc.cadn.net.cn

平原CommandHandlingResult具有 message 和 exit code。spring-doc.cadn.net.cn

无效spring-doc.cadn.net.cn

具有 void 返回类型的方法被视为已完全处理异常。通常 您可以定义Terminal作为方法参数,并使用 Terminal Writer 从中写入响应。由于异常已完全处理,因此在这种情况下使用 Exit code 0。spring-doc.cadn.net.cn