简体   繁体   中英

Exception handling in Spring MVC with 3 layer architecture

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");
}

You should handle exceptions in service layer only, as part of design unless required. Think of the requirement where you need a same functionality deleteMenu for some other mapping too.

From any design point of view. Keep controller very specific to handling model attributes only serving the request mapping to business logic. Keep a method in service layer to take menuGroupId and throw exception from that service if parameter is thrown or DB error has occurred.

Refer more: Model-View-Controller, what every part really does?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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