springmvc在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。
一、异常处理思路
系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理
1.定义异常处理器的实现类
/**
* 异常处理器的自定义的实现类
*
*/
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
Exception e) {
// 发生异常的地方Service层。obj:包名+类名+方法名(形参)字符串
// 日志的作用:我们开发过程中控制台是可以看到错误信息的。
// 另外,项目以war包的形式发布到tomcat,tomcat在linux服务器上,通过日志观察程序运行状态
ModelAndView mav = new ModelAndView();
mav.addObject("error", "未知异常");
mav.setViewName("error");
return mav;
}
}
2.交给spring管理
springmvc.xml文件
<bean class="com.ken.exception.CustomExceptionResolver" />
3.创建error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-16"
pageEncoding="UTF-16"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-16">
<title>Insert title here</title>
</head>
<body>
${error }
</body>
</html>
4.在程序中编写异常代码
5.测试
二、自定义异常
1.自定义异常
public class MessageException extends Exception {
private static final long serialVersionUID = -7309558270984127106L;
private String msg;
public MessageException(String msg) {
super();
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
2.改造异常处理器的自定义的实现类
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
Exception e) {
// 发生异常的地方Service层。obj:包名+类名+方法名(形参)字符串
// 日志的作用:我们开发过程中控制台是可以看到错误信息的。
// 另外,项目以war包的形式发布到tomcat,tomcat在linux服务器上,通过日志观察程序运行状态
ModelAndView mav = new ModelAndView();
// 判断异常类型
if (e instanceof MessageException) {
//预期异常
MessageException me = (MessageException) e;
mav.addObject("error", me.getMsg());
} else {
mav.addObject("error", "未知异常");
}
mav.setViewName("error");
return mav;
}
}
3.代码中添加预期的异常
4.测试