SpringMVC异常处理

211 阅读1分钟

前序

在前面编写的控制层(或其他层)类方法中,可能会出现种种的异常,这些异常会逐层向上抛出,然后在页面中显示错误信息。

可能出现的一种错误信息

如果我们希望在方法中出现异常后显示的是另一种特定的页面,而不是干巴巴的显示错误页面的不友好页面,我们可以使用异常处理器来处理异常。

示例

请求链接

<a href="handlerException/testException">模拟错误场景</a>

控制层类

@RequestMapping("/handlerException")
@Controller
public class handlerExceptionController {
    @RequestMapping("/testException")
    public String testException() throws SysException{
        System.out.println("testException方法执行");
        try {
            int a = 2 / 0;      //模拟异常
        }catch (Exception e) {
            e.printStackTrace();
            throw new SysException("查询所有用户信息出现错误");
        }
        return "success";
    }
}

自定义异常以及异常处理类

public class SysException extends Exception{
    private String message;

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
public class SysExceptionResolver implements HandlerExceptionResolver {
    //处理异常的业务逻辑
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        SysException se = null;
        if(se instanceof SysException) {
            se = (SysException)e;
        }else {
            se = new SysException("系统正在维护");
        }
        ModelAndView mav = new ModelAndView();
        mav.addObject("errorMsg", se.getMessage());
        mav.setViewName("error");
        return mav;
    }
}

在springmvc.xml中配置异常处理器

<!--    配置自定义的异常处理器-->
<bean id="sysExceptionResolver" class="com.on1.exception.resolver.SysExceptionResolver"/>

跳转到的错误页面error.jsp

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

此时的项目结构:

点击链接后跳转到的页面error:

此时控制台输出: