我正在构建一个简单的具有 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
并在抛出参数或发生数据库错误时从该服务抛出异常。
关于java - 三层架构 Spring MVC 中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24095713/