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>

解析

原文地址:https://www.cnblogs.com/Ryuichi/p/13388083.html