异常处理器
SpringMVC在处理请求的过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。
异常处理的思路
系统中的异常包括两类:预期异常和运行时异常,前者通过捕获异常从而获取异常信息,后者主要同通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由SpringMVC前端控制器交由异常处理器进行异常处理,如下图:
自定义异常类
为了区别不同的异常,通常根据异常类型进行区分,这里创建一个自定义系统异常。
如果controller、service、dao抛出此类异常说明是系统预期处理的异常信息。
public class MyException extends Exception {
//异常信息
private String message;
public MyException() {
super();
}
public MyException(String message) {
super();
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
自定义异常处理器
public class textHandleException implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception exception) {
// 定义异常信息
String message;
// 判断异常类型
if (exception instanceof MyException) {
// 如果是自定义异常,读取异常信息
message = exception.getMessage();
} else {
// 如果是运行时异常,则取错误堆栈,从堆栈中获取异常信息
Writer out = new StringWriter();
PrintWriter s = new PrintWriter(out);
exception.printStackTrace(s);
message = out.toString();
}
// 把错误信息发给相关人员,邮件,短信等方式
// 返回错误页面,给用户友好页面显示错误信息
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", message);
modelAndView.setViewName("error");
return modelAndView;
}
}
异常处理器的配置
在springmvc.xml文件中添加:
<!-- 配置全局异常处理器 -->
<bean
id="customHandleException" class="cn.bigdata.ssm.exception.CustomHandleException"/>
错误页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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-8">
<title>Insert title here</title>
</head>
<body>
<h1>系统发生异常了!</h1>
<br />
<h1>异常信息</h1>
<br />
<h2>${message}</h2>
</body>
</html>
测试异常
当以上的文件都已配置完成后,我们可以在Controller的代码中一个方法中加入异常代码,如 int i= 1 / 0 ,使代码出错。之后我们运行代码看效果即可。
404错误页面处理
上述的异常处理是指500异常的处理方式。以下为404页面的处理。
方法一:
直接在web.xml文件中进行配置,代码如下:
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/errors/404.jsp</location>
</error-page>
若url匹配不到则会跳转到404.jsp页面。
方法二:
直接在Controller层中写入以下方法:
@RequestMapping("*")
public String test3(){
return "404";
}
如果不能精确匹配上url,则返回404.jsp页面