Exception handling in Spring MVC with 3 layer architecture

Posted by Chorochrondochor on Stack Overflow See other posts from Stack Overflow or by Chorochrondochor
Published on 2014-06-07T09:19:30Z Indexed on 2014/06/07 9:24 UTC
Read the original article Hit count: 227

Filed under:
|
|

I am building a simple web applications with 3 layers - DAO, Service, MVC. When in my Controller I want to delete menu group and it contains menus I am getting ConstraintViolationException.

Where should I handle this exception? In DAO, Service, or in Controller? Currently I am handling the exception in Controller.

My code below.

DAO method for deleting menu groups:

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

    getCurrentSession().delete(e);
}

Service method for deleting menu groups:

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

Controller method for deleting menu groups in 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");
}

© Stack Overflow or respective owner

Related posts about java

Related posts about spring