【问题标题】:Handling Exception in Spring boot Application with Hibernate使用 Hibernate 处理 Spring Boot 应用程序中的异常
【发布时间】:2017-12-14 03:09:37
【问题描述】:

我正在使用 Spring boot 构建一个 REST API,并且 DAO 层是在 Hibernate 中实现的。我需要了解在应用程序中抛出和处理异常的正确方法。目前我正在这样做

@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 子句(抛出异常)并在服务层捕获并将其包装在自定义异常(未经检查的异常)中,并且不在控制器层传播异常。 它是否正确 ?还是有更好的方法?

【问题讨论】:

    标签: java hibernate rest spring-boot


    【解决方案1】:

    对于您不想专门处理的所有情况,我建议您使用通用 @ExceptionHandler({Exception.class})。 也可以为需要自定义处理的情况创建单独的异常类。

    这取决于你想要达到什么目标。 关于你的情况。 DAO 层中的异常并不一定意味着请求错误或未提供正确的参数。它可能是映射问题、数据库访问问题等。所以我不会将它包装到我的自定义异常中,或者至少包装到一般DataAccessException,围绕它进行良好的日志记录并向客户端返回一些一般错误代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多