Spring MVC|異常處理

異常處理的思路

  系統中異常包括兩類,預期異常和運行時異常 RuntimeException,前者通過捕獲異常從而獲取異常信息,後者主要通過規範代碼開發、測試等方法減少運行時異常的發生。
  系統的dao、service、controller出現異常後全部 throws Exception 向上拋出,最後由 springmvc 前端控制器交由異常處理器進行異常處理,如下圖:
1.PNG

實現步驟

  1. 自定義一個異常類和錯誤界面。
  2. 自定義異常處理器(實現HandlerExceptionResolver接口)。
  3. 把自定義的異常處理器加入到 IOC 容器中(使用@Component註解或者xml配置)。

實現示例

自定義一個異常類

/**
 * 自定義異常類
 */
public class CustomException extends Exception{
    private String message;

    public CustomException(String message) {
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

友好的錯誤界面(交給前端人員)

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>錯誤界面</title>
</head>
<body>
    ${error_msg}
</body>
</html>

自定義異常處理器並加入到 IOC 容器中

/**
 * 自定義異常處理器
 */
@Component
public class MvcResolverExceptionResolver implements HandlerExceptionResolver {
    /**
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o 當前對象
     * @param e 捕獲到的異常
     * @return ModelAndView
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        e.printStackTrace();
        MvcResolveException mvcResolveException = null;
        //如果該異常爲自定義異常,則直接強轉
        if (e instanceof MvcResolveException) {
            mvcResolveException = (MvcResolveException) e;
        } else {
        //不是,則直接創建一個系統異常對象
            mvcResolveException = new MvcResolveException("服務器出小差了,請稍後...");
        }
        ModelAndView modelAndView = new ModelAndView();
        //把錯誤信息加入到request域中
        modelAndView.addObject("error_msg", mvcResolveException.getMessage());
        modelAndView.setViewName("error");//跳轉到錯誤界面
        return modelAndView;
    }
}

異常處理演示

  在 controller 方法中手動製造一個異常。

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/exceptionResolver")
    public String testExceptionResolver() throws CustomException {
        try {
            int i = 2 / 0;
        } catch (Exception e) {
            throw new CustomException("發生CustomException異常了");
        }
        return "success";
    }
}

  請求這個方法。

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
    <a href="user/exceptionResolver">點擊測試</a>
</body>
</html>
發佈了46 篇原創文章 · 獲贊 1 · 訪問量 2505
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章