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