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