簡體   English   中英

使用Hibernate處理Spring Boot應用程序中的異常

[英]Handling Exception in Spring boot Application with Hibernate

我正在使用Spring Boot構建一個REST API,並且Hibernate中實現了DAO層。我需要了解在應用程序中拋出和處理Exception的正確方法,目前我正在以這種方式進行操作

@Repository
public class UserDaoImpl
{
     public getAllUsers() throws Exception
     {
          //get All Users from DB
    }
}

@Service
public class UserServiceImpl
{
    public getAllUsers throws MyCustomException
   {    try{
           userDaoImpl.getAllUsers();
         }
       catch(Exception e)
         {
             throw MyCustomException();
         }

   }         

}

和異常映射器

@ControllerAdvice
public class ApplicationExceptionHandler extends ResponseEntityExceptionHandler {   

@ExceptionHandler({MyCustomException.class})
  @ResponseBody
  public ResponseEntity<?> handleCustomException(Exception e) {
    log.error("", e);
    Map<String, String> error = new HashMap<String, String>();
    error.put("message", e.getMessage());
    return new ResponseEntity<>(error, HttpStatus.NOT_ACCEPTABLE, MessageResource.getLogMessage("BAD_REQUEST_EXCEPTION"));
  }

}  

public class MyCustomException extends RuntimeException
{   
     ///// ....


}

因此,我在DAO層中添加了throws子句(throws Exception),並在服務層進行了捕獲,並將其包裝在Custom Exception(未檢查的異常)中,並且不在控制器層中傳播該異常。 這個對嗎 ? 還是有更好的方法?

對於不希望專門處理的所有情況,我建議您使用常規的@ExceptionHandler({Exception.class}) 同樣,可以為需要自定義處理的情況創建單獨的異常類。

這取決於您要實現什么。 關於你的情況。 DAO層中的異常不一定意味着請求錯誤或未提供正確的參數。 可能是映射問題,數據庫訪問問題等。因此,我不會將其包裝到我的自定義異常中,或者至少將其包裝到一般的DataAccessException ,從而很好地記錄下來並將一些一般的錯誤代碼返回給客戶端。

暫無
暫無

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

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