我使用controller->service->dao架构构建了一个spring应用程序。DAO对象使用hibernate。这些服务是带注释的@Transactional。
我试图捕获服务中的道异常,将它们包装起来,然后将它们抛给我的控制器:
服务
@Override
public Entity createEntity(Entity ent) throws ServiceException {
try {
return entityDAO.createEntity(ent);
} catch (DataAccessException dae) {
LOG.error("Unable to create entity", dae);
throw new ServiceException("We were unable to create the entity for the moment. Please try again later.", dae);
}
}控制器
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String createEntity(@ModelAttribute(value = "newEntity") Entity newEntity, RedirectAttributes redirectAttributes) {
try {
entityService.createEntity(newEntity);
} catch (ServiceException se) {
redirectAttributes.addFlashAttribute("error", se.getMessage());
}
}
return "redirect:/entity/manage";
}然而,即使在服务级别捕捉到了DataAccessException,它仍然以某种方式一直冒泡到我的控制器上。
例如,如果我在数据库级别上不满足唯一的字段条件,则会得到一个HTTP错误500,如下所示:
org.hibernate.AssertionFailure: null id in com.garmin.pto.domain.Entity entry (don't flush the Session after an exception occurs)发布于 2015-08-19 20:31:30
代码是缓存DataAccessException而不是HibernateException,尝试缓存HibernateException
发布于 2015-08-19 21:01:00
如果要在Controller中处理异常,请不要在服务中捕获它。
服务
@Override
public Entity createEntity(Entity ent) throws DataAccessException {
return entityDAO.createEntity(ent);
}控制器
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String createEntity(@ModelAttribute(value = "newEntity") Entity newEntity, RedirectAttributes redirectAttributes) {
try {
entityService.createEntity(newEntity);
} catch (DataAccessException e) {
redirectAttributes.addFlashAttribute("error", e.getMessage());
}
return "redirect:/entity/manage";
}或者,如果您想利用Spring来处理异常,请使用ExceptionHandler注释。您可以在网上找到好的教程,例如,Spring @ExceptionHandler示例。
发布于 2015-08-19 21:12:37
使异常翻译工作
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />https://stackoverflow.com/questions/32103090
复制相似问题