1、定义自定义异常类,继承Exception
public class CustomException extends Exception {
private static final long serialVersionUID = 1L;
public String message; //错误信息
public Throwable throwable; //Java中所有异常和错误的基类
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Throwable getThrowable() {
return throwable;
}
public void setThrowable(Throwable throwable) {
this.throwable = throwable;
}
public CustomException(String message) {
super();
this.message = message;
}
public CustomException(Throwable throwable) {
super();
this.throwable = throwable;
}
}
2、定义异常处理器
public class CustomExceptionResolver implements HandlerExceptionResolver {
//异常处理
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
// 解析出异常类型
CustomException customException = null;
String message = "";
// 若该异常类型是系统自定义的异常,直接取出异常信息在错误页面展示即可。
if(ex instanceof CustomException){
customException = (CustomException)ex;
message = customException.getMessage();
}
else{
// 如果不是系统自定义异常,构造一个系统自定义的异常类型,信息为“未知错误”
customException = new CustomException("操作错误");
message = customException.getMessage();
}
//输出错误信息,便于在控制台查错
System.out.println("发生错误了,错误信息如下:");
System.out.println(ex);
System.out.println();
//错误信息
ModelAndView modelAndView = new ModelAndView();
//将错误信息传到页面
modelAndView.addObject("message",message);
//指向错误页面
modelAndView.setViewName("showError");
return modelAndView;
}
}
3、SpringMVC中配置全局异常处理器
<bean id="exceptionResolver" class="com.wwz.eshop.exception.CustomExceptionResolver"></bean>
4、编写jsp页面showError.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误页面</title>
</head>
<body>
<h2>出错了</h2>
<hr>
<p>${ message }</p>
</body>
</html>
5、异常处理思路
如上图所示,系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。