1. 程式人生 > 實用技巧 >9、SpringMVC異常處理解決方案

9、SpringMVC異常處理解決方案

1、自定義異常類

/**
 * 自定義異常類
 */
public class SysException extends Exception{
    //儲存提示資訊
    private String message;

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

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

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

2、處理異常業務邏輯

public class SysExceptionResolver implements HandlerExceptionResolver{
    /**
     * 處理異常業務邏輯
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param ex
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {

        //獲取到異常物件
        SysException e = null;
        if(ex instanceof SysException){
            e = (SysException)ex;
        }else{
            e = new SysException("系統正在維護");
        }

        //建立ModelAndView物件
        ModelAndView mv = new ModelAndView();
        mv.addObject("errorMsg", e.getMessage());

        mv.setViewName("error");
        return mv;
    }
}

3、配置異常處理器

<!--配置異常處理器-->
    <bean id="sysExceptionResolver" class="com.example.exception.SysExceptionResolver"></bean>

4、請求頁

<a href="testException">異常處理</a>

5、控制器

@Controller
public class UserController {
    @RequestMapping("/testException")
    public String testException() throws SysException {

        try {
            //模擬異常
            int i= 10/0;
        } catch (Exception e) {
            //列印異常資訊
            e.printStackTrace();
            //丟擲自定義異常資訊
            throw new SysException("分母不能為零");
        }
        return "success";
    }
}

6、錯誤頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${errorMsg}
</body>
</html>

解析