簡體   English   中英

即使我們在catch塊中處理異常,如何使用@ControllerAdvice在Spring中處理異常

[英]How to handle exception in spring with @ControllerAdvice even though we are handling exception in catch block

當方法被try和catch塊包圍時,無法使用@ControllerAdvice和@AfterThrowing。

我可以逐步解釋

步驟1:在我的Spring應用程序中,所有處理程序(方法)均通過try and catch塊處理異常。

步驟2:因此要求我需要在所有處理程序方法中均發生異常時觸發電子郵件。 但是我的應用程序有100多種方法。 因此,嘗試使用@ControllerAdvice通過使用@ExceptionHandler批注來處理異常。 我知道它不會起作用,因為我們已經在catch代碼塊中處理了異常。 因此,它無法查看@ControllerAdvice。

步驟3:我也嘗試使用Aop @AfterThrowing建議。 它不起作用。 因此,我無法刪除整個應用程序代碼中的所有catch塊。 做到這一點非常困難。

但是我的問題是,即使我們正在處理異常,春季是否有辦法處理異常。 我們返回狀態碼,例如400。 在春季,他們會提供任何建議以標識狀態碼。
因為正在將ResponseEntity Status退回作為響應。

@RequestMapping(value = "/service/getDetails", method = RequestMethod.POST, produces = { "application/json" })
public ResponseEntity<Map<String, Object>> getDetails(@RequestBody Details details, HttpServletRequest request) {
    ResponseEntity<Map<String, Object>> response = null;
    try {
        /// Some code
    } catch (Exception e) {
        logger.error("Exception while DetailsController: " + e.getMessage());
        response = new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        /*
         * int status=response.getStatusCodeValue();
         * scheduledMailTrigerService.sendErrorLogInfo(request,e,status);
         */
    }
    return response;
}

  @ControllerAdvice
  public class AppExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = { Exception.class })
public String handleAnyException(Exception ex, WebRequest request) {
    System.out.println("Done");
    return "Done";
}

}

您可以使用@Around建議來捕獲方法執行的結果...我的建議是,您從所有端點中刪除try catch,只編寫包裹ProceedingJoinPointproce proceed()執行的try catch。 這樣,您可以在發生異常時返回ResponseEntity 400 ,並執行電子郵件發送邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM