【发布时间】: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