[英]Java Spring exception handling
我有多個控制器,它們的異常在ControllerAdvice
中處理。 所有控制器都使用常見的異常類型(如HttpClientException, DBException
等)。 但是有一個特定的 controller 應該以不同的方式處理異常。
在我當前的實現中,此特定 controller 的所有方法都用 try-catch 包裝,並在出現任何異常時拋出CustomException
。 然后,在ControllerAdvice
中我處理這種類型的異常。
但是,我想處理ControllerAdvice
中的所有異常,並擺脫 controller 方法中的CustomException
和 try-catch。
有什么辦法可以在異常提示中找出來源 controller 名稱嗎? 我可以檢查它並以不同方式處理異常。 或者也許存在其他解決方案?
在您的 controller 建議中,您可以為您的自定義異常提供處理程序,如下所示。
@ControllerAdvice
public class CustomGlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
public final ResponseEntity<ApiResponseDTO> manageException(CustomException ex) {
log.error("Error in CustomException: {}", ex.getMessage(), ex);
ApiResponseDTO error = ApiResponseDTO.builder()
.message(ex.getMessage())
.result(0)
.build();
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(CustomException1.class)
public final ResponseEntity<ApiResponseDTO> manageException1(CustomException1 ex) {
log.error("Error in CustomException1: {}", ex.getMessage(), ex);
ApiResponseDTO error = ApiResponseDTO.builder()
.message(ex.getMessage())
.result(0)
.build();
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public final ResponseEntity<ApiResponseDTO> manageException1(Exception ex) {
log.error("Error in Common Exception Handler: {}", ex.getMessage(), ex);
StackTraceElement[] ste = ex.getStackTrace();
String className=ste[ste.length - 1].getClassName();
System.out.println(className);
if(className.equalsIgnoreCase("com.a")){
System.out.println("Do A related stuff");
}else{
System.out.println("Do B related stuff");
}
ApiResponseDTO error = ApiResponseDTO.builder()
.message(ex.getMessage())
.result(0)
.build();
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
}
如上一個塊所述,您可以從拋出此異常的位置獲取 class 名稱,並使用該名稱來分支您的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.