java - 三层架构 Spring MVC 中的异常处理

标签 java spring spring-mvc

我正在构建一个简单的具有 3 层的 Web 应用程序 - DAO、Service、MVC。当在我的 Controller 中我想删除菜单组并且它包含菜单时,我收到 ConstraintViolationException。

我应该在哪里处理这个异常?在 DAO、Service 中,还是在 Controller 中?目前我正在 Controller 中处理异常。

下面是我的代码。

删除菜单组的DAO方法:

@Override
public void delete(E e){
    if (e == null){
        throw new DaoException("Entity can't be null.");
    }

    getCurrentSession().delete(e);
}

删除菜单组的服务方法:

@Override
@Transactional(readOnly = false)
public void delete(MenuGroupEntity menuGroupEntity) {
    menuGroupDao.delete(menuGroupEntity);
}

Controller 中删除菜单组的 Controller 方法:

@RequestMapping(value = "/{menuGroupId}/delete", method = RequestMethod.GET)
public ModelAndView delete(@PathVariable Long menuGroupId, RedirectAttributes redirectAttributes){
    MenuGroupEntity menuGroupEntity = menuGroupService.find(menuGroupId);

    if (menuGroupEntity != null){
        try {
            menuGroupService.delete(menuGroupEntity);
            redirectAttributes.addFlashAttribute("flashMessage", "admin.menu-group-deleted");
            redirectAttributes.addFlashAttribute("flashMessageType", "success");
        } catch (Exception e){
            redirectAttributes.addFlashAttribute("flashMessage", "admin.menu-group-could-not-be-deleted");
            redirectAttributes.addFlashAttribute("flashMessageType", "danger");
        }
    }

    return new ModelAndView("redirect:/admin/menu-group");
}

最佳答案

除非需要,否则您应该仅在服务层处理异常,作为设计的一部分。考虑一下您还需要相同功能 deleteMenu 来进行其他映射的需求。

从任何设计角度来看。保持 Controller 非常具体地处理模型属性,仅服务于映射到业务逻辑的请求。在服务层保留一个方法来获取 menuGroupId 并在抛出参数或发生数据库错误时从该服务抛出异常。

引用更多:Model-View-Controller, what every part really does?

关于java - 三层架构 Spring MVC 中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24095713/

相关文章:

java - JpaRepository 与 EntityManager

java - 无法发送 48681 字节的消息来保护来自 java 的 wcf 服务

java - 在Java中获取键盘/鼠标输入

java - 重复drawLine()来绘制垂直条Java

java - 如何从Spring java配置@Configuration类中获取WEB-INF资源?

java - 使用JPA在 "or"语句中为空

java - 在 Spring 中,@RequestParameter 注释不接受 defaultValue 参数的 boolean 值,它只适用于字符串 URL 请求参数

java - org.hibernate.MappingException : No Dialect mapping for JDBC type: 2000

java - 简单的 spring boot web 应用程序不起作用,whitelabel 错误页面

java - 带过滤链的 Spring 配置