SpringMVC自定义异常
1、 自定义异常类
//自定义异常类
public class CustomerException extends RuntimeException {
public CustomerException(String msg){
super(msg);
}
}
2、 自定义异常处理器
public class CustomerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("error",e.getMessage());//接收 错误的异常信息
modelAndView.setViewName("error");
return modelAndView;
}
}
3、错误页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>错误页面</title>
</head>
<body>
<%--出错了 请联系管理员--%>
${error}
</body>
</html>
4、 异常处理器配置
在springmvc.xml中添加:
<!--统一的异常处理-->
<bean class="com.baidu.exception.CustomerExceptionResolver"></bean>
5、 异常测试
@RequestMapping("c6")
@Controller
public class Controller6 {
//模拟异常
@RequestMapping(value = "edit.action")
public String edit(){
if(1==1){
throw new CustomerException("出异常了"); //自定义的异常信息
}
return "list";
}
}