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