簡體   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