异常处理器
系统中异常分类
预期异常:
在编译阶段检测的异常,
使用IDEA开发工具的话,代码刚写写完,立马检测
运行时异常(runtimeException):
在代码运行的过程中报错的,
只能通过规范代码、测试等手段减少运行时异常发生
异常处理器思路
系统的DAO、Service、Controller层,每一层都有可能抛 出 异常,所有层的异常都通过throws Exception往上抛,最后由SpringMVC的前端控制器交给异常处理器进行异常处理:
异常处理
自定义异常处理器
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("error","未知异常");
modelAndView.setViewName("/static/error.jsp");
return modelAndView;
}
}
异常处理器配置
在springmvc中设置:
<!--springMVC全局异常处理器-->
<bean class="com.huadian.controller.CustomExceptionResolver"></bean>
错误页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<html>
<head>
<title>Title</title>
</head>
<body>
${error}
</body>
</html>
异常处理测试
在controller中制作一个错误
@Controller
public class ProductController {
@Autowired
private ProductService productService;
@RequestMapping(value = "/product/productList.action")
public ModelAndView itemList(){
System.out.println("itemList........");
int i = 5/0;//自己创建一个异常。
List<Product> list = productService.getProductList();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject( "productList", list);
modelAndView.setViewName( "/static/productList.jsp" );
//
return modelAndView;
}
自定义异常处理
自定义异常
public class MseeageException extends Exception {
private String msg;
public MseeageException(String message) {
this.msg = message;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
异常处理器修改
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) {
ModelAndView modelAndView = new ModelAndView();
if (e instanceof MseeageException){
modelAndView.addObject("error",((MseeageException) e).getMsg());
}else {
modelAndView.addObject("error","未知异常");
}
modelAndView.setViewName("/static/error.jsp");
return modelAndView;
}
}
测试
@RequestMapping(value = "/product/toEdit.action")
public ModelAndView toEdit(Integer id) throws MseeageException {
System.out.println("toEdit.....id...");
if (id==null){
throw new MseeageException("id不能为空");
}
Product product = productService.getProductById(id);
ModelAndView modelAndView = new ModelAndView();
//productList和JSP页面的Key一致
modelAndView.addObject( "item", product);
modelAndView.setViewName( "/static/editProduct.jsp" );
return modelAndView;
}