@ExceptionResolver
@ShellComponent 类可以拥有 @ExceptionResolver 方法来处理组件方法中的异常。这些方法旨在用于带注解的方法。
异常可能匹配正在传播的顶级异常(例如,直接抛出的 IOException),或者匹配包装异常中的嵌套原因(例如,包装在 IllegalStateException 中的 IOException)。这可以匹配任意原因级别。
对于匹配的异常类型,最好将目标异常声明为方法参数,如前面的示例所示。当多个异常方法匹配时,通常优先选择根异常匹配而不是原因异常匹配。更具体地说,ExceptionDepthComparator 用于根据异常与抛出异常类型的深度对异常进行排序。
或者,注解声明可以缩小要匹配的异常类型,如以下示例所示
@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,它将用作控制台的输出。您可以使用 @ExitCode 注解来定义返回码。
@ExceptionResolver
@ExitCode(code = 5)
String errorHandler(Exception e) {
return "Hi, handled exception";
}
返回类型为 void 的 @ExceptionResolver 会自动作为已处理的异常进行处理。如果需要向控制台写入内容,您可以定义 @ExitCode 并使用 Terminal。
@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();
}