springMvc自定义异常类,使用异常处理器去处理异常.欢迎交流学习
附一张网络图,解释了异常处理的机制。
定义异常类
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;
}
}
定义异常处理器
public class SysExceptionResolver implements HandlerExceptionResolver {
/**
* 异常处理器接口
* @param httpServletRequest
* @param httpServletResponse
* @param o 代表当前对象
* @param e
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
//判断当前的异常类型是否是自定义异常类型
// 是 就抛出 不是就重新new一个对象
if(!(e instanceof SysException)){
e = new SysException("系统正在维护");
}
使用modelAndView对象返回到前端
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg",e.getMessage()); //取到SysException异常类的错误信息
mv.setViewName("error");
return mv;
}
}
Controller表现层
@Controller
public class UserController {
@RequestMapping("/find")
public String userFind() throws SysException {
System.out.println("controller方法执行了");
// 模拟异常
try {
int a = 10 / 0;
} catch (Exception e) {
e.printStackTrace();
//抛出自定义异常类让异常处理器类去处理
throw new SysException("查询用户出现了异常呀");
}
return "success";
}
}
error页面(接受ModelAndView对象返回的异常message)
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%-- ModelAndView存的信息相当于存在request中,所以用request去取--%>
<%--注意:isELIgnored="false"这个一定要有 不然jsp不认识el表达式--%>
<h1 style="color:deeppink">${requestScope.errorMsg}</h1>
</body>
</html>
在springMvc.xml中配置异常处理器
<!--配置异常处理器bean对象-->
<bean id="sysExceptionResolver" class="cn.itcast.exception.SysExceptionResolver"></bean>