我正在尝试使用 Spring MVC 处理自定义异常。 DAO 层异常处理程序由服务层和服务层包装该异常,并由 Spring MVC 的 Controller 异常处理程序处理该异常。以下是我的代码:
@Override
public void saveNewMachineDetails(Machine machine, Configurations configurations) throws DataNotPersist{
logger.info("call service saveNewMachineDetails method");
try{
machineRepository.saveAndFlush(machine);
}catch(Exception ex){
// logger.error(ex.getMessage());
DataNotPersist dataNotPersist = new DataNotPersist(messageSource.getMessage("code.object.notpersist", null, null),
messageSource.getMessage("msg.object.notpersist", new Object[]{"Machine"}, null), ex);
throw dataNotPersist;
}}
在上面的代码中,DAO 层异常在服务层进行处理,并将该异常包装在自定义异常中并抛出该异常。
在 Web 层中,我配置了异常处理程序来处理异常,但是当引发异常时,处理程序不会捕获异常,我认为是因为我无法用自定义异常包装实际异常。以下是我的异常处理程序代码:
@ControllerAdvice
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = DataNotPersist.class)
public ModelAndView defaultExceptionHandler(HttpServletRequest request, DataNotPersist ex)throws Exception {
logger.info("In GlobalExceptionHandler");
logger.debug("********* : "+ex.getMessage());
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", ex);
modelAndView.addObject("url", request.getRequestURL());
modelAndView.setViewName("common/error");
return modelAndView;
}}
最佳答案
在服务层中,当我抛出异常时, Spring 回滚事务并将我的Exception
包装到TransactionException
中查看。现在我使用我的 Exception
类处理事务回滚,如下所示:
@Override
@Transactional(value="transaction_manager", rollbackFor={DataNotPersist.class})
public void saveNewMachineDetails(Machine machine, Configurations configurations) throws DataNotPersist{
logger.info("call service saveNewMachineDetails method");
try{
machineRepository.saveAndFlush(machine);
}catch(DataAccessException ex){
logger.error(ex.getMessage());
DataNotPersist dataNotPersist = new DataNotPersist(messageSource.getMessage("code.object.notpersist", null, null),
messageSource.getMessage("msg.object.notpersist", new Object[]{"Machine"}, null), ex);
throw dataNotPersist;
}}
关于java - 无法使用Spring MVC在服务层包装DAO异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28295684/