@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();
}