繁体   English   中英

Spring MVC具有三层架构的异常处理

[英]Exception handling in Spring MVC with 3 layer architecture

我正在构建一个具有3层的简单Web应用程序-DAO,Service,MVC。 在我的控制器中时,我想删除菜单组并且它包含的菜单正在获取ConstraintViolationException。

我应该在哪里处理该异常? 在DAO,服务还是在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的需求。

从任何设计角度来看。 保持控制器对处理模型属性非常特定,该模型属性仅用于将请求映射到业务逻辑。 如果抛出了参数或发生了DB错误,则在服务层中保留一个方法来获取menuGroupId并从该服务中引发异常。

请参阅更多内容: Model-View-Controller,每个部分实际上是做什么的?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM