【问题标题】:Spring MVC handling exceptionsSpring MVC 处理异常
【发布时间】:2015-08-19 18:33:53
【问题描述】:

我已经使用 controller->service->dao 架构构建了一个 spring mvc 应用程序。 DAO 对象正在使用休眠。服务注释为@Transactional

我正在尝试在服务中捕获 dao 异常,将它们包装起来,然后将它们扔给我的控制器:

服务

@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)

【问题讨论】:

标签: spring hibernate spring-mvc


【解决方案1】:

代码正在缓存 DataAccessException 而不是 HibernateException,请尝试缓存 HibernateException

Is there a way to translate HibernateException to something else, then DataAccessException in sping

【讨论】:

    【解决方案2】:

    如果要在Controller中处理异常,不要在Service中捕获。

    服务

    @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 MVC @ExceptionHandler Example

    【讨论】:

      【解决方案3】:

      使异常翻译工作

      1. 您必须使用 @Repository 注释您的 DAO
      2. 确保您已声明此 bean <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

      【讨论】:

        【解决方案4】:

        Here 是一篇关于在 Spring MVC 项目中处理异常的不同方法的精彩帖子。

        其中,我发现使用@ControllerAdvice 类可以在一个地方全局处理所有异常,这通常是最方便的。 Spring Lemon 的源代码可以作为一个很好的具体例子。

        【讨论】:

          猜你喜欢
          • 2018-03-20
          • 1970-01-01
          • 2016-12-30
          • 2015-01-24
          • 2016-11-18
          • 1970-01-01
          • 1970-01-01
          • 2011-07-20
          • 2011-10-08
          相关资源
          最近更新 更多