参考Spring Framework 中文文档 - 22. Web MVC 框架 | Docs4dev
自定义异常
public class GlobalExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg",ex.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
applicationContext.xml里面加入
<!--把自定义异常加入ioc-->
<bean id="globalExceptionHandler" class="com.zhang.handler.GlobalExceptionHandler"></bean>
error.jsp
<%--
Created by IntelliJ IDEA.
User: 98090
Date: 2021/8/26
Time: 21:49
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
测试
@Controller
@RequestMapping("ex")
public class TestExceptionController {
@GetMapping("testEx")
public String testEx(){
System.out.println("执行");
try {
int i = 10/0;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("错误");
}
return "seccess";
}
}