1. 异常处理思路
Controller调用service,service调用dao,异常都是向上抛出的,最终有DispatcherServlet找异常处理器进行异常的处理。
2. SpringMVC的异常处理
controller代码
java
@Controller
@RequestMapping("/role")
public class RoleController {
/**
* 自己处理异常
* @return
@RequestMapping("/findAll.do")
public String findAll(){
try {
System.out.println("执行了...");
// 模拟异常
int a = 10/0;
} catch (Exception e) {
e.printStackTrace();
// 跳转到友好提示页面
}
return "suc";
}
*/
/**
* 使用异常处理器方式
* @return
*/
@RequestMapping("/findAll.do")
public String findAll(){
System.out.println("执行了...");
// 模拟异常
int a = 10/0;
return "suc";
}
}
自定义异常类
java
public class SysException extends Exception{
// 提示消息
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SysException(String message) {
this.message = message;
}
}
自定义异常处理器
java
public class SysExceptionResolver implements HandlerExceptionResolver {
/**
* 程序出现了异常,调用异常处理器中的方法
* @param o
* @param e
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
// 在控制台打印异常的信息
e.printStackTrace();
// 做强转
SysException exception = null;
// 判断
if(e instanceof SysException){
exception = (SysException)e;
}else{
exception = new SysException("系统正在维护,请联系管理员");
}
// 存入异常提示信息
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg",e.getMessage());
// 设置跳转的页面
mv.setViewName("error");
return mv;
}
}
配置异常处理器
XML
<bean id="sysExceptionResolver" class="com.qcbyjy.demo3.SysExceptionResolver" />
jsp代码
html
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>错误提示页面</title>
</head>
<body>
<!-- 异常测试 -->
<h3>异常测试(会跳到 error.jsp)</h3>
<a href="${pageContext.request.contextPath}/role/findAll.do">模拟除 0 异常</a>
</body>
</html>