在 Springmvc 框架中,如果配置了异常处理器的话,那么底层产生并往上层抛出的异常在传到前端控制器后,会交由配置的异常处理器进行处理并返回提示页面给客户端,具体流程如下:
- 自定义异常类
在实际开发中,我们处理异常,一般使用自定义的异常类。
public class MyException extends Exception {
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public MyException(String msg) {
this.msg = msg;
}
}
- 控制器处理方法:模拟异常发生的位置
@Controller
@RequestMapping("test")
public class testController {
@RequestMapping("exception")
public String testException() throws Exception{
System.out.println("testException");
// 模拟 service 层处理出现异常
try{
int num = 10 / 0;
}catch (Exception e){
e.printStackTrace();
// 抛出自定义异常
throw new MyException("错误信息:除数不能为0!");
}
// 异常发生后,不会执行以下代码
return "success";
}
}
- 自定义异常处理器:异常层层向上抛出后,来到异常处理器中进行处理
public class ExceptionResolver implements HandlerExceptionResolver {
/**
* 异常处理器处理异常的方法
* @param httpServletRequest 请求对象
* @param httpServletResponse 回复对象
* @param o 处理器对象
* @param e 异常对象
* @return ModelAndView对象
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
// 获取异常对象
MyException myException = null;
if(e instanceof MyException){
myException = (MyException)e;
}else{
myException = new MyException("其他异常信息...");
}
// 创建ModelAndView对象
ModelAndView mv = new ModelAndView();
mv.addObject("error", myException);
mv.setViewName("error");
return mv;
}
}
- 在 springmvc.xml 文件中配置自定义的异常处理器:
<!-- 配置异常处理器 -->
<bean id="exceptionResolver" class="com.lyj.exception.ExceptionResolver" />
- 测试页面:index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="test/exception">测试异常</a>
</body>
</html>
- 测试异常显示页面:error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>异常处理</title>
</head>
<body>
${error.msg}
</body>
</html>
- 测试结果: