1.系统中异常包括两类
- 前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理
2.自定义异常类
package com.huan.entity;
public class CustomException extends Exception{
public String message;
public CustomException(String message){
super(message);
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
3.全局异常处理器
package com.huan.entity;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CustomExceptionResolver implements HandlerExceptionResolver{
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;
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;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>错误信息</title>
</head>
<body>
<h1>错误信息</h1>
${message}
</body>
</html>
<!--全局异常处理器,实现HandlerExceptionResolver接口就是全局异常处理器-->
<bean class="com.huan.entity.CustomExceptionResolver"></bean>
4.异常测试
查找的用户不存在抛出异常
public List<User> findItemsById(Integer id) throws Exception {
List<User> UserList= userService.findUser();
if(UserList==null){
throw new CustomException("用户为空!");
}
return UserList;
}