6.异常处理
6.1异常处理思路
系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发送。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。 springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。
6.2自定义异常类
对不同的异常类型定义异常类,继承Exception。
public class CustomException extends Exception {
// 异常信息
private String message; public CustomException(String message) {
super();
this.message = message;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} }
6.3全局异常处理器
思路:
系统遇到异常,在程序中手动抛出,dao抛出service、service给controller、controller抛给前端控制器,前端控制器调用全局异常处理器。
全局异常处理器处理思路:
解析出异常类型
如果该异常是系统自定义的异常,直接取出异常信息,在错误页面展示
如果该异常类型不是系统自定义的异常,构造一个自定义的异常类型(信息为“未知错误”) springmvc提供一个HandlerExceptionResolver接口
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
//handler就是处理器适配器要执行Handler对象(只有method)

// 解析出异常类型
// 如果该 异常类型是系统 自定义的异常,直接取出异常信息,在错误页面展示
// String message = null;
// if(ex instanceof CustomException){
// message = ((CustomException)ex).getMessage();
// }else{
如果该 异常类型不是系统 自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)
// message="未知错误";
// }

//上边代码变为
CustomException customException = null;
if(ex instanceof CustomException){
customException = (CustomException)ex;
}else{
customException = new CustomException("未知错误");
}

//错误信息
String message = customException.getMessage();


ModelAndView modelAndView = new ModelAndView();

//将错误信息传到页面
modelAndView.addObject("message", message);

//指向错误页面
modelAndView.setViewName("error");
return modelAndView;
} 6.4错误页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示</title>
</head>
<body>
<h1>${message }</h1>
</body>
</html>