簡體   English   中英

如何使用通用異常處理程序捕獲異常?

[英]How to catch exceptions using a general exception handler?

我有這段代碼,我在其中向服務發出請求,如果沒有具有該 ID 的部門,我在服務類中的方法將拋出一個自定義異常,當我捕獲異常時,我會在該控制器的方法中捕獲該異常,我將帶有錯誤消息和 HTTP 狀態的響應實體返回到端點。 我被告知我不需要在這里捕獲異常,我只需要在通用異常處理程序中捕獲它。 現在我不明白那是什么意思。

 @GetMapping("/departments/{departmentId}")
    public ResponseEntity<Object> getDepartmentById(@PathVariable("departmentId") Long departmentId) {
        DepartmentDTO departmentDTO = null;
        logger.debug("Entering get item by id endpoint");
        try {
            departmentDTO = departmentService.getDepartmentById(departmentId);
            logger.info("Returned department with id: " + departmentId);
        } catch (ApiException e) {
            logger.error("Unable to return department with ID: " + departmentId + " ,message: " + e.getMessage(), e);
            return GeneralExceptionHandler.handleExceptions(e);
        }
        return ResponseEntity.ok().body(departmentDTO);

    }

這是我的異常處理類

@ControllerAdvice
public class GeneralExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GeneralExceptionHandler.class);
    @ExceptionHandler(value = {ApiException.class})
    public static ResponseEntity<Object> handleExceptions(ApiException e) {
        logger.info("Exception handled:"+e.getMessage()+" with http status: "+e.getHttpStatus());
        return new ResponseEntity<>(e.getMessage(), e.getHttpStatus());
    }
}

要使用通用異常處理程序,您可以刪除控制器方法中的 try-catch 塊,只讓異常被拋出。 然后異常將被 GeneralExceptionHandler 類中的 @ExceptionHandler 方法捕獲。

您的控制器可以簡化為以下內容:

@GetMapping("/departments/{departmentId}")
public ResponseEntity<Object> getDepartmentById(@PathVariable("departmentId") Long departmentId) {
    logger.debug("Entering get item by id endpoint");
    DepartmentDTO departmentDTO = departmentService.getDepartmentById(departmentId);
    logger.info("Returned department with id: " + departmentId);
    return ResponseEntity.ok().body(departmentDTO);
}

如果在 departmentService.getDepartmentById 方法中拋出 ApiException,它將被您的 GeneralExceptionHandler 類中的 @ExceptionHandler 方法捕獲,該方法將記錄異常並返回包含 ApiException 中指定的錯誤消息和 HTTP 狀態代碼的響應。

這樣,您可以將異常處理邏輯集中在 GeneralExceptionHandler 類中,避免在多個控制器中重復異常處理代碼。

暫無
暫無

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

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