一 SpringMVC中异常处理的思路
1. 系统中异常包括两类
编译时异常和运行时异常 RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
2. SpringMVC中异常处理的思路
系统的 dao、service、controller 出现都通过 throws Exception 向上抛出,最后由 springmvc 前端控制器交由异常处理器进行异常处理,如下图:
二 案例
1. 编写index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="user/testException">测试异常......</a>
</body>
</html>
2. 编写错误页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>错误页面</h3>
${message}
</body>
</html>
3. 编写异常类,做提示信息的
package cn.itcast.exception;
//自定义异常
public class SysException extends Exception {
private String message;
public SysException(String message) { this.message = message; }
@Override
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
}
4. 编写异常处理器
异常处理器,必须实现HandlerExceptionResolver
package cn.itcast.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SysExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
ex.printStackTrace();
SysException sysException = null;
//如果抛出的是系统自定义异常则直接转换
if(ex instanceof SysException){
sysException = (SysException)ex;
}else{
//如果抛出的不是系统自定义异常则重新构造一个系统错误异常。
sysException = new SysException("系统错误,请与系统管理员联系!");
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", sysException.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
5. 在applicationContext.xml中配置异常处理器
<!--配置异常处理器-->
<bean id="sysExceptionResolver" class="cn.itcast.exception.SysExceptionResolver"></bean>
6. 模拟抛出异常的处理器
package cn.itcast.controller;
import cn.itcast.exception.SysException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testException")
public String testException() throws SysException {
System.out.println("testException执行了......");
//模拟从service层抛回来异常
try {
int i=10/0;
} catch (Exception e) {
e.printStackTrace();
throw new SysException("查询用户信息失败....");
}
return "success";
}
}
7. 结果